获取两个线程执行的输出

时间:2015-11-02 22:37:21

标签: java multithreading scjp

以下是来自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(); 
     }
}

可能的结果是什么?

一个。 0,2,4,4,6,8,10,6,

B中。 0,2,4,6,8,10,2,4,

℃。 0,2,4,6,8,10,12,14,

d。 0,0,2,2,4,4,6,6,8,8,10,10,12,12,14,14,

电子。 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14,

在转储中它说答案是A和C.但是,我不知道答案A是如何可能的,因为最后一个输出(6)小于之前的输出。

2 个答案:

答案 0 :(得分:0)

A - 如果一个线程打印0,2,则可能两个都获得4到当前并且将6个保存到x(两个),然后两个都获得6到当前,第二个到达结束 - 打印6,8,10,之后首先打印6。

答案 1 :(得分:0)

由于有两个线程同时运行...

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
相关问题