A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Java黑马 中级黑马   /  2015-7-4 17:42  /  495 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

实现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();
  }
  }

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马