Java code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class SelfManaged implements Runnable {
  private int countDown = 5;
  private Thread t = new Thread(this);
  public SelfManaged() { t.start(); }
  public String toString() {
    return Thread.currentThread().getName() +
      "(" + countDown + "), ";
  }
  public void run() {
    while(true) {
      System.out.print(this);
      if(--countDown == 0)
        return;
    }
  }
  public static void main(String[] args) {
    for(int i = 0; i < 5; i++)
      new SelfManaged();
  }
} /* Output:
java编程思想英文第4版,1137 页,第二自然段," but you should be aware that starting threads inside a constructorcan be quite problematic, because another task might start executing before the constructorhas completed, which means the task may be able to access the object in an unstable state",作者的意思是,不宜在构造里开启线程,因为有可能新的线程启动时,构造还未执行完,这时等于在用这个新线程来驱动一个不稳定的任务对象(毕竟构造未执行完,初始化任务还未做完)。我的疑问在于:示例代码中,t.start()放在构造函数最后一行,这时只t.start()语句执行完,接着构造函数也执行完了(函数返回是原子操作,t.start()后面无其他语句,所以执行构造函数的线程不会中断),然后新的线程才会启动。不明白作者为何还说示例代码有问题,而且在后来的示例代码中,作者多次都在构造里启动线程(放在构造最后一行)。总之我的意思是:只要保证在构造最后一行启动线程,那么在构造中启动线程就完全不会有任何问题,不是我的看法是否正确。求指点!能有反例代码最好!
                    
                    
                添加回答
举报
0/150
	提交
		取消
	
 
                    