public class TestDeadLock implements Runnable {
2 /*public*/ int flag = 1;
3 static Object o1 = new Object();
4 static Object o2 = new Object();
5 public void run () {
6 System.out.println("flag="+flag);
7 if(flag==1) {
8 synchronized(o1) {//其实就是花括号了,应该是synchronized的花括号了,而对于死锁的问题,应该是在往里面嵌套一个,而不是并列,这/是为什么我出错的原因了
9 try {
10 Thread.sleep(1000);
11 } catch (InterruptedException e) {}
12 synchronized(o2) {
13 System.out.println("1");
14 }
15 }
16 }
17 if(flag==0) {
18 synchronized(o2) {
19 try {
20 Thread.sleep(1000);
21 } catch (InterruptedException e) {}
22 synchronized(o1) {
23 System.out.println("0");
24 }
25 }
26 }
27 }
28 public static void main(String args[]) {
29 TestDeadLock tdl = new TestDeadLock();
30 TestDeadLock tdl2 = new TestDeadLock();
31 tdl.flag = 1;
32 tdl2.flag = 0;
33 Thread t1 = new Thread(tdl);
34 Thread t2 = new Thread(tdl2);
35 t1.start();
36 t2.start();
37 }
38 }
找了两天就是没弄成死锁,现在被我发现了,就是一个花括号,应该是嵌套的,不是并列的