This is a question from the k&b practice exams book and has me confused. The correct answers are ABC according to the answer key. I understand those, but to me, D also seems a valid answer. The book says that D is incorrect because the value of id swaps between 0 and 1, and there is no chance for the same method to be executed twice.
But what if one
thread modifies id, and the other thread stills sees the old value of id because id is not volatile? Then both threads could call the pick method, one after the other. Please advise.
public class Stone implements Runnable {
static int id = 1;
public void run() {
try {
id = 1 - id;
if(id == 0) { pick(); } else { release(); }
} catch(Exception e) { }
}
private static synchronized void pick() throws Exception {
System.out.print("P ");
System.out.print("Q ");
}
private synchronized void release() throws Exception {
System.out.print("R ");
System.out.print("S ");
}
public static void main(
String[] args) {
Stone st = new Stone();
new Thread(st).start();
new Thread(st).start();
} }
Which are true? (Choose all that apply.)
A. The output could be P Q R S
B. The output could be P R S Q
C. The output could be P R Q S
D. The output could be P Q P Q
E. The program could cause a deadlock.
F. Compilation fails.