Given:
public class Thread1 {
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 void go() {
Runnable r1 = new Runner();
new Thread(r1).start();
new Thread(r1).start();
}
public static void main(String[] args) {
new Thread1().go();
}
}
Which two are possible results? (Choose two)
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,
I chose A and B but I’m not certain if that is the correct answer.
First of all D. and E. are out. As
iscope local to the function, we know that there is going to be 8 numbers.Now
B. 0, 2, 4, 6, 8, 10, 2, 4,is incorrect. Why? In order print the last two positions each thread has to write the variable
xat least two times. At this point the minimum value forxis4. Which means that whatever the race conditions, the last two values should be greater or equal to4.EDIT
Cis totally possible. Absence of synchronization doesn’t mean it is not possible to have what is called a serial execution (ie as if threads execute one after another). The lesson from concurrency is that you don’t know how threads will be interleavedhappens for example :
xbefore the second startcurrent = x;, the second finish executing and the first continue.As Brian Goetz said: