I'm prepping for the SCJP, and multithreading has been my shakiest area, mostly because I don't know how to look at multithreading code and walk through it. So far my approach has been to write down in English what might be happening in each thread and testing a few cases with threads randomly intersecting each other, which is a really hit-and-miss and time-consuming approach. So I'd like to see how a pro would go about it. Would you be willing to read the code below (it's the latest question that's giving me trouble) and write down what goes through your head (code-related stuff only, please :) as you work out the possible outputs? The choices that come with the question are at the end. What I'm looking for isn't the solution, which I have, but how one arrives at the solution efficiently on the exam.
And yeah, I know this question doesn't have a precise answer, etc etc. Accepted vote goes to the answer that's clearest and easiest to emulate, okay :)
Thanks everyone!
Question: Which of these answers are possible outputs?
public class Threads1 {
int x = 0;
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();
}
}
Choices (choose all that apply):
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,