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

再来个线程的问题...
class   Test   {
    private   int   x;
    public     void   foo()   {
          int   current   =   x;
          x   =   current   +   1;
    }
    public   void   go()   {
            for(int   i=0;i <3;i++)   {
                new   Thread()   {
                      public   void   run()   {
                            foo();    
                            System.out.print(x   + ", ");//line   12
                      }}.start();
            }
    }
}
   
class   A{
    public   static   void   main(String[]   args){
            Test   a   =   new   Test();
            a.go();
    }
}

  Move   the   line   12   print   statement   into   the   foo()   method.
上面的改变可以确保输出是1,2,3么?

我认为不可以..
首先foo()就变成了:
    public     void   foo()   {
          int   current   =   x;
          x   =   current   +   1;
          System.out.print(x   + ", ");
    }
假设线程0先输出了1,然后线程1执行foo(),假设在执行完x   =   current   +   1;的时候,线程2开始执行了,这时x   =2吧..然后再输出..最后线程1把System.out.print(x   + ", ")最后执行了..
那不是最后是1,3,3了么??

不知道我哪里理解错了...

------解决方案--------------------
输出 1 ,2 ,3
每一次循环都启动了一个线程 ,执行了foo()方法,然后输出x的值。

//线程的结束 等同 一次循环的结束 (执行一遍循环体)

------解决方案--------------------
改造了一下你的程序,希望使你所要的:
class Test implements Runnable{
private int x;
public void foo(){
x++;
}
public void run() {
synchronized(this){
foo();
try{
Thread.sleep(1000);
}catch(Exception e){
}
System.out.println(Thread.currentThread().getName()+ ", "+x);
}
}
}

class ThreadTest{
public static void main(String[] args){
Test a = new Test();
for(int i=0; i <3; i++){
new Thread(a).start();
}
}
}