实现Runnable接口
可以解决单继承的局限性,查询API可获知Thread类实现了Runnable接口。
使用Runnable接口启动线程的步骤:
(1)建立Runnable接口实例对象
(2)以Runnable接口实例对象创建Thread实例对象
(3)调用Thread线程对象的start()方法
public class Writer implements Runnable{
private String name;
public Writer(String name){
this.name=name;
}
public void run(){
while(true){
System.out.println(name+"抽支烟歇歇");
System.out.println(name+"写一段文稿");
try {
Thread.sleep((int)(Math.random()*10000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Writer w1=new Writer("作者1");
Writer w2=new Writer("作者2");
Thread t1=new Thread(w1);
Thread t2=new Thread(w2);
t1.start();
t2.start();
}
}
|
|