2016-12-03 59 views
-1
public class RunTest { 
    public static int counter = 0; 
    static class RunnerDec implements Runnable{ 
     public void run(){ 
      for(int i=0;i<5000; i++){ 
       counter--; 
      } 
     } 
    } 

    static class RunnerInc implements Runnable{ 
     public void run(){ 
      for(int i=0;i<5000; i++){ 
       counter++; 
      } 
     } 
    } 

    public static void main(String[] args) { 
     RunnerDec rd = new RunnerDec(); 
     RunnerInc ri = new RunnerInc(); 
     Thread t1 = new Thread(rd); 
     Thread t2 = new Thread(ri); 
     t1.start();  
     t2.start(); 
     try{ 
      t1.join(); // this will stop the main thread until t1 is done incrementing 5000 times 
      t2.join(); // this will stop the main thread until t2 is done incrementing 5000 times 
     }catch(Exception e){ 
      e.printStackTrace(); 
     } 
     System.out.println(counter); 
    } 

} 

我希望结果是每次都是0,但这不是这种情况。 java文档说join()“等待这个线程死掉”。我觉得主线程应该等待t1完成然后等待t2完成。这不是正在发生的事情。感谢您的澄清!Java线程连接()行为

+0

你觉得'开始'做什么? –

回答

2

它确实等待线程死亡。但是你的两个线程同时更新一个共享变量而没有任何同步,所以你看到了竞争条件和可见性问题。

例如:

counter = 1000 
thread 1 reads counter : 1000 
thread 2 reads counter : 1000 
thread 1 increments and writes counter: 1001 
thread 2 decrements and writes counter: 999 

由于++和 - 不原子操作,上述螺纹交织例如失去一个增量。

解决它们的最简单方法是使用AtomicInteger而不是int。为了理解问题的关键,你最好阅读Java Concurrency in Practice,或者至少阅读Java并发教程。