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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 一碗小米周 中级黑马   /  2013-9-22 19:58  /  705 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 一碗小米周 于 2013-9-22 21:07 编辑

看了张老师的交通灯的视频,我想请问下各位,为什么Thread.sleep()不能直接放在构造方法中,需要独立创建一个线程?谢谢。

评分

参与人数 1技术分 +1 收起 理由
黄兴旺 + 1

查看全部评分

2 个回复

倒序浏览
  1. public class Road {
  2.         private List<String> vehicle = new ArrayList<String>();
  3.         private String  name = null;
  4.         public Road(final String name){
  5.                 this.name = name;
  6.                 ExecutorService pool = Executors.newSingleThreadExecutor();
  7.                 pool.execute(new Runnable() {
  8.                     public void run() {
  9.                             for(int i =1;i<100;i++){
  10.                                      try {
  11.                                         Thread.sleep((new Random().nextInt(10)+1)*1000);
  12.                                 } catch (InterruptedException e) {
  13.                                        
  14.                                         e.printStackTrace();
  15.                                 }
  16.                                     vehicle.add(name+"--"+i);
  17.                                   }
  18.                                
  19.                         }
  20.                 });
复制代码
回复 使用道具 举报
Thread.sleep()是让运行该代码的线程暂停。构造函数是给类初始化的,只运行一次。把它放在构造函数里面,创建Road对象的时候,是主函数创建,主线程会暂停。主线程暂停了就不能运行其它的代码了。
在构造函数里面用线程池的技术,是建立完对象后,也同时建立了一个线程,然其运行我们想要它运行的代码。这就比你让Road类继承Thread类或实现Runnable方法,然后建立对象,然后启动线程要简便多了。

评分

参与人数 1技术分 +1 收起 理由
黄兴旺 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马