日期:2014-05-20  浏览次数:20751 次

thinking in java 中的一个不理解地方,请大家多多指教
情况是这样的:(一些没用的代码我去掉了)
public class SelfManaged implements Runnable {
  private Thread t = new Thread(this);
  public SelfManaged() { t.start(); } *******关键就是这里
  public String toString() {
  }
  public void run() {
......
  }
} /* Output:

然后书上说了:
  This example is quite simple and
therefore probably safe, but you should be aware that starting threads inside a constructor
can be quite problematic, because another task might start executing before the constructor
has completed, which means the task may be able to access the object in an unstable state

就是红色的这句话我不懂,难道在一般的多线程情况下,构造函数的执行是不会被打断的?


------解决方案--------------------
构造函数里面的执行的线程当然有可能会被打断。


翻译一下就是 因为另外的任务可能会在构造函数执行完之前就开始执行 也就是说构造函数可能在一个不稳定的情况下去读取一个对象。(就是说对象会被another task所改变)

不明白LZ什么问题哇?
------解决方案--------------------
引用楼主 galimatoo 的帖子:
情况是这样的:(一些没用的代码我去掉了)
public class SelfManaged implements Runnable {
private Thread t = new Thread(this);
public SelfManaged() { t.start(); } *******关键就是这里
public String toString() {
}
public void run() {
......
}
} /* Output:

然后书上说了:
This example is quite simple and
therefore probably safe, but you should be aware th…

------解决方案--------------------
在构造器执行完之前其他任务(线程)可能启动,这就意味着线程可能在一个不安全的状态下达到目标.

理解一下。。。
------解决方案--------------------
探讨
我觉得红字说明的并不是“构造函数的执行是不会被打断的”,

而是在构造函数完成构造之前可能有其他的线程在运行,从而造成了对象的不稳定。

------解决方案--------------------
探讨
在构造器执行完之前其他任务(线程)可能启动,这就意味着线程可能在一个不安全的状态下达到目标.

理解一下。。。

------解决方案--------------------
Java code

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:
Thread-0(5), Thread-0(4), Thread-0(3), Thread-0(2), Thread-0(1), Thread-1(5), Thread-1(4), Thread-1(3), Thread-1(2), Thread-1(1), Thread-2(5), Thread-2(4), Thread-2(3), Thread-2(2), Thread-2(1), Thread-3(5), Thread-3(4), Thread-3(3), Thread-3(2), Thread-3(1), Thread-4(5), Thread-4(4), Thread-4(3), Thread-4(2), Thread-4(1),
*///:~

------解决方案--------------------
探讨
引用:
在构造器执行完之前其他任务(线程)可能启动,这就意味着线程可能在一个不安全的状态下达到目标.

理解一下。。。

我觉得后面半句应该翻译为 “这就意味着线程可能以一种不稳定的状态访问对象”

------解决方案--------------------
例如,在一个构造函数中创建的线程可以访问正被创建的对象,既使此对象没有完全被创建。 

设置x 为 -1 的线程可以和设置 x 为 0 的线程同时进行。所以,此时 x 的值无法预测。 

------解决方案--------------------
从线程内部构造

能够相当棘手,因为另一项任务可能会开始之前执行构造

已经完成,这意味着任务可以访问的对象处于不稳定的状态
所以构造函数里面的执行的线程当然有可能会被打断。 


------解决方案--------------------