日期:2014-05-20  浏览次数:20919 次

多线程中有趣的输出~~~~
Question 130
Click the Exhibit button.
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.


答案为:ABE
A,E是对得,我理解。
可是B。。。

这段程序,在不发生死锁的情况下,R1总是要-5+2-1,R2总是要+5-2+1

根据加法交换律和加法结合率- - R1相当于-4,R2相当于+4。

就算线程导致运算时间不同,也不该出现5和15啊~~~

------解决方案--------------------
很好理解啊,doTransfer和main是不同线程
执行了doTransfer(r1, r2, 5);后
如果System.out.println先执行完,就是5,15