10. public class Transfers {
11. public static void main(String[] args) throws Exception {
12. Record r1 = new Record();
13. Record r2 = new Record();
14. doTransfer(r1, r2, 5);
15. doTransfer(r2, r1, 2);
16. doTransfer(r1, r2, 1);
17. // print the result
18. System.out.println(”rl = “ + r1.get() +“, r2=” + r2.get());
19. }
20. private static void doTransfer(
21. final Record a, final Record b, final int amount) {
22. Thread t = new Thread() {
23. public void run() {
24. new Clerk().transfer(a, b, amount);
25. }
26. };
27. t.start();
28. }
29. }
30. class Clerk {
31. public synchronized void transfer(Record a, Record b, int amount){
32. synchronized (a) {
33. synchronized (b) {
34. a.add(-amount);
35. b.add(amount);
36. }
37. }
38. }
39. }
40. class Record {
41.int num=10;
42. public int get() { return num; }
43. public void add(int n) { num = num + n; }
44. }
If Transfers.main() is run, which three are true? (Choose three.)
A. The output may be “r1 = 6, r2 = 14”.
B. The output may be “r1 = 5, r2 = 15”.
C. The output may be “r1 = 8, r2 = 12”.
D. The code may run (and complete) with no output.
E. The code may deadlock (without completing) with no output.
F. M IllegalStateException or InterruptedException may be thrown at
runtime.
Answer is....
ABE.
I got no ideas about these answer. I guess the answer is r1 = 10, r2 = 10 which same as I run it in Java Program. I don't understand why is ABE. anyone can help?
2 comments:
Hi, one thing u need to know is that the java Threading behavior is ALWAYS unpredictable (here we r talking about the thread running sequence), especially in a multi-processor environment!
We have 4 threads created here, one is the main thread and 3 are created by calling the doTransfer() method.
So for your own result, it's because the main thread executes before the extra 3 threads.
To be continue...
For answer A, assume its in a perfect world, all child threads executed before the main thread executes System.out.println().
For answer B, base on the following thread running sequence:
1) 1st child thread
2) main thread
3) main(mother) thread end, other child threads die
C is false because there is no matching thread sequence.
E is true because if i) 1st & 2nd child threads or ii) 2nd & 3rd child threads run at the same time, deadlock occurs.
Here is the deadlock story. Assume 2 child threads (t1 and t2) run at the same time after line 32, t1 get lock for object r1 and t2 get lock for object r2. After that t1 will wait for lock of r2 and t2 will wait for lock of r1, but both of them won't give up their own object lock, so deadlock occur. This is just a 2 threads deadlock story, if more thread here the case will be more complicated.
Post a Comment