复制代码
- <BLOCKQUOTE>
- <P> </P>
- <P>你拿的根本就不是同一锁,当然不会出现死锁,对你的代码修改如下:</P>
复制代码
- 01.public class TestDeadLock implements Runnable{
- 02. public int flag = 2;
- 03. static Object o1 = new Object();
- 04. static Object o2 = new Object();
- 05.
- 06. public void run(){
- 07. if(flag == 1){
- 08. synchronized(o1){
- 09. System.out.println("锁住o1");
- 10. try {
- 11. Thread.sleep(5000);
- 12. }catch(Exception e){}
- 13. }
- 14.
- 15. synchronized(o2){
- 16. System.out.println("1");
- 17. }
- 18. }
- 19. //疑问:无法死锁
- 20.
- public synchronized void run2()
- {
- if(flag == 0){
- 21. synchronized(o1){
- 22. System.out.println("锁住o2");
- 23. try {
- 24. Thread.sleep(5000);
- 25. }catch(Exception e){}
- 26. }
- 27.
- 28. synchronized(o1){
- 29. System.out.println("2");
- 30. }
- 31. }
- 32. }
- }
- 34. public static void main(String[] args){
- 35. TestDeadLock td1 = new TestDeadLock();
- 36. TestDeadLock td2 = new TestDeadLock();
- 37. td1.flag = 1;
- 38. td2.flag = 0;
- 39. Thread t1 = new Thread(td1);
- 40. Thread t2 = new Thread(td2);
- 41. t1.start();
- 42. t2.start();
- 43. }
- 44.}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |