第8行或16行如何發生死鎖?同步中的死鎖
1. public class DeadlockRisk {
2. private static class Resource {
3. public int value;
4. }
5. private Resource resourceA = new Resource();
6. private Resource resourceB = new Resource();
7. public int read() {
8. synchronized(resourceA) {
9. synchronized(resourceB) {
10. return resourceB.value + resourceA.value;
11. }
12. }
13. }
14
15. public void write(int a, int b) {
16. synchronized(resourceB) {
17. synchronized(resourceA) {
18. resourceA.value = a;
19. resourceB.value = b;
20. }
21. }
22. }
23. }
沒有死鎖,因爲讀取和寫入不會被調用:-) –
當線程讀取鎖定資源A時,*同時*線程寫入鎖定資源B,因此兩個線程都無法鎖定下一個資源,因爲它們彼此鎖定: ) – 2013-07-16 13:57:25