Getting the output with two threads executing

199 Views Asked by At

Here is a question from SCJP dump:

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(); 
     }
}

What are the possible results?

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, 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,

In the dump it says the answers are A and C. However, I don't know how answer A can be possible since the last output (6) is smaller than the outputs before.

2

There are 2 best solutions below

0
Rustam On

A - possible if one thread prints 0, 2, then both get 4 to current and saves 6 to x (both), then both get 6 to current, and second goes to end - prints 6, 8, 10, after that first prints 6.

0
Pankaj Kumar On

Since there are two threads running 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