java吧 关注:1,238,076贴子:12,707,943
  • 2回复贴,共1

新人求教 死锁问题

取消只看楼主收藏回复

public class TestDeadLock implements Runnable {
public int flag = 1;
static Object o1 = new Object(), o2 = new Object();
public void run() {
System.out.println("flag=" + flag);
if(flag == 1) {
synchronized(o1) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized(o2) {
System.out.println("1");
}
}
}
if(flag == 0) {
synchronized(o2) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized(o1) {
System.out.println("0");
}
}
}
}
public static void main(String[] args) {
TestDeadLock td1 = new TestDeadLock();
TestDeadLock td2 = new TestDeadLock();
td1.flag = 1;
td2.flag = 0;
Thread t1 = new Thread(td1);
Thread t2 = new Thread(td2);
t1.start();
t2.start();
}
}
为什么定义的static Object o1 = new Object(), o2 = new Object();要加static,我试了把它去掉就构不成死锁了,求大神解释下。。


IP属地:上海1楼2015-08-10 15:39回复
    public class TestDeadLock implements Runnable {
    public int flag = 1;
    static Object o1 = new Object(), o2 = new Object();
    public void run() {
    System.out.println("flag=" + flag);
    if(flag == 1) {
    synchronized(o1) {
    try {
    Thread.sleep(500);
    } catch (Exception e) {
    e.printStackTrace();
    }
    synchronized(o2) {
    System.out.println("1");
    }
    }
    }
    if(flag == 0) {
    synchronized(o2) {
    try {
    Thread.sleep(500);
    } catch (Exception e) {
    e.printStackTrace();
    }
    synchronized(o1) {
    System.out.println("0");
    }
    }
    }
    }
    public static void main(String[] args) {
    TestDeadLock td1 = new TestDeadLock();
    TestDeadLock td2 = new TestDeadLock();
    td1.flag = 1;
    td2.flag = 0;
    Thread t1 = new Thread(td1);
    Thread t2 = new Thread(td2);
    t1.start();
    t2.start();
    }
    }


    IP属地:上海2楼2015-08-10 15:43
    回复
      为什么定义的static Object o1 = new Object(), o2 = new Object();要加static,我试了把static去掉就构不成死锁了,求大神解释下。


      IP属地:上海3楼2015-08-10 15:45
      回复