i've been trying to get ready for the SCJP exam that i have to take next week, and i've encountered this question about Java Threads.
1-public class Stone implements Runnable {
2- static int id = 1;
3-
4- public void run() {
5- try {
6- id = 1 - id;
7- if (id == 0) {
8- pick();
9- } else {
10- release();
11- }
12-
13- } catch (Exception e) {
14- }
15- }
16-
17- private static synchronized void pick() throws Exception {
18- System.out.print("P ");
19- System.out.print("Q ");
20- }
21-
22- private synchronized void release() throws Exception {
23- System.out.print("R ");
24- System.out.print("S ");
25- }
26-
27- public static void main(String[] args) {
28- Stone st = new Stone();
29- new Thread(st).start();
30- new Thread(st).start();
31- }
32-}
- Which are true? (Choose all that apply.)
- The output could be P Q R S
- The output could be P R S Q
- The output could be P R Q S
- The output could be P Q P Q
- The program could cause a deadlock.
- Compilation fails.
The answer key says:
A, B, and C are correct. Since pick() is static and release() is non-static, there
are two locks. If pick() was non-static, only A would be correct.
It also says that the output P Q P Q is not really an option and It's not possible to get such results.
At the beginning, i didn't really believe the answer key, but then i saw that it's really not possible to see this output as a result of this application. (After running the class.)
Now, that's the part that confuses me a little bit, And here is why
I thought a P Q P Q or an R S R S result must have been possible. Because there is always a chance for a situation that makes the variable id exactly same for both threads. In other words, for example, when the first thread just finished executing the line 6 it could give up its turn to the other one, and after that, the other one could change the value of the variable id and then voila! They could go in to same if block happily.
I tried to see this situation over and over again (with Eclipse Juno and Java 7). It just doesn't happen. I'm sure that there something wrong with my way of thinking, and i wonder to know what it is. I need to know what is the rule that hinders these two threads to access the variable id at its same state.
1-id
!? and how are you really sure about only just one thread at time would be line 7?