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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 张 涛 中级黑马   /  2012-9-15 10:24  /  1308 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 张 涛 于 2012-9-18 14:56 编辑

如果想在一个对象被new出时就创建一个线程,把线程写在他的构造方法里,结果成这样:
  1. public class AAA implements Runnable {
  2. String name;

  3. AAA(String name){
  4. this.name = name;
  5. new Thread(new AAA()).start();
  6. }

  7. @Override
  8. public void run() {
  9. ....
  10. }
  11. }
复制代码
但是,这样执行不久死循环了吗?有其他方法吗?实现在构造方法里开启线程。

3 个回复

倒序浏览
构造方法中可以new 对象,也可以调用对象的方法……应该可以的……当然,建议在构造方法中new和start的是其他线程对象的线程……不然是会逐渐占有资源直到死掉。。。
回复 使用道具 举报
本帖最后由 佟亚鹏 于 2012-9-15 10:42 编辑

楼主,这个是可以使的,使用jdk5的线程库,在构造方法内启动线程,Executors里面包括了大量的操作线程的静态方法,Executors.newSingleThreadExecutor().execute( command),这个方法可以执行一个Runnable接口的实例,逻辑放在run里面,举个例子
  1. public class Test  {
  2.         public Test() {
  3.                 Executors.newSingleThreadExecutor().execute(
  4.                                 new Runnable() {
  5.                                         public void run() {
  6.                                                 System.out.println("execute start");
  7.                                                 try {
  8.                                                         //让这个线程休息2秒
  9.                                                         Thread.sleep(2000);
  10.                                                 } catch (InterruptedException e) {
  11.                                                         e.printStackTrace();
  12.                                                 }
  13.                                                 //打印当前时间
  14.                                                 System.out.println("execute " + new Date().toLocaleString());
  15.                                                 System.out.println("execute end");
  16.                                         }                                       
  17.                                 });
  18.                 System.out.println("Test construtor " + new Date().toLocaleString());        
  19.         }
  20.         
  21.         public static void main(String[] args) {
  22.                 new Test();
  23.         }
  24. }
复制代码
打印结果:
execute start
Test construtor 2012-9-15 10:36:47
execute 2012-9-15 10:36:49
execute end
从打印的时间可以看出,代码分路径了。。。。。希望能够帮助到你

回复 使用道具 举报
可以的。建议你看下张老师的交通灯管理系统的视频,该系统中有两个类都在构造方法中定义了线程。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马