2015-11-02 24 views
0

这里的输出是SCJP转储一个问题:掌握两个线程执行

public class Threads1 { 
    int x=0; 
    public class Runner implements Runnable{ 
      public void run(){ 
       int current=0; 
       for (int i=0; i<4; i++){ 
        current = x; 
        System.out.print(current + ','); 
        x=current +2; 
       } 
      } 
    } 

    public static void main(String[] args){ 
      new Threads1().go(); 
    } 

    public void go(){ 
      Runnable r1 = new Runner(); 
      new Thread(r1).start(); 
      new Thread(r1).start(); 
    } 
} 

可能是什么结果?

A. 0,2,4,4,6,8,10,6,

B. 0,2,4,6,8,10,2,4,

C. 0,2,4,6,8,10,12,14,

D. 0,0,2,4,4,6,6,8,8,10,10,12,12, 14,14,

E. 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14,

在转储它说答案是A和C.但是,我不知道h由于最后一个输出(6)比之前的输出小,所以可以回答A。

回答

0

A - 如果一个线程打印出0,2,那么两者都可以得到4到当前并将6保存到x(两者),然后两者都得到6到当前,第二个结束 - 打印6,8,10,首先打印后6

0

由于有两个线程运行simulataneously ...

It might result in the following at every iteration you are adding +2 
thread 1- 0 2 4 6 8 10 
thread 2-  4  6