情况是这样的:(一些没用的代码我去掉了)
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
就是红色的这句话我不懂,难道在一般的多线程情况下,构造函数的执行是不会被打断的?

解决方案 »

  1.   

    构造函数里面的执行的线程当然有可能会被打断。
    翻译一下就是    因为另外的任务可能会在构造函数执行完之前就开始执行 也就是说构造函数可能在一个不稳定的情况下去读取一个对象。(就是说对象会被another task所改变)不明白LZ什么问题哇?
      

  2.   


    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),
    *///:~很明显 LZ可以去试试看  output的内容并不是总是书上说的那样  因为这5个线程并不是一个一个执行的在一开始 i=0 的时候 产生一个线程(由构造函数产生) 但并不是说等这个线程执行5次之后 才会有main方法产生另一个i=1的线程所以书上的意思很明显 构造函数并不能保证对象的稳定  因为main中产生的其他方法可能会影响到构造函数中对象的值
      

  3.   

    例如,在一个构造函数中创建的线程可以访问正被创建的对象,既使此对象没有完全被创建。 设置x 为 -1 的线程可以和设置 x 为 0 的线程同时进行。所以,此时 x 的值无法预测。 
      

  4.   

    access object 翻译为 实例化对象?
      

  5.   

    呵呵,可能作者只想表达一个很简单的意思

    本来情况下一个构造函数只有在被完整构造结束后(构造函数返回)才会传引用给其它类或方法使用,
    但这里没等它构造函数返回就已经把这个“不完整对象”的引用this传给了一个线程,从而这个线程执行时有可能会不小心用了这个“不完整对象”

    吧,总觉得作者没有必要在这里加上这么一个“转折”因为假使这样的话也只要把 t.start(); 放到构造函数最后就应该没有问题了
      

  6.   

    跟进学习.......俺也是Thinking in Java 的读者...