java吧 关注:1,233,163贴子:12,700,747
  • 0回复贴,共1

多线程的死锁问题

只看楼主收藏回复

public class TestSynDead {
public static void main(String[] args) {
// TODO Auto-generated method stub
DeadLock d1=new DeadLock();
d1.flag=1;
Thread t1=new Thread(d1);
DeadLock d2=new DeadLock();
d2.flag=0;
Thread t2=new Thread(d2);
t1.start();
t2.start();
}
}
class DeadLock implements Runnable{
public static Object o1=new Object();
public static Object o2=new Object();
int flag=0;
public void run(){
System.out.println("flag="+flag);
if(flag==1){
synchronized(o1){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized(o2){
System.out.println("1 o2 ");
}
}
if(flag==0){
synchronized(o2){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized(o1){
System.out.println("0 o1 ");
}
}
}
}
这是演示死锁的问题,但是输出的结果却是正确的:
flag=1
flag=0
1 o2
0 o1
不知道哪里的问题?谢谢


IP属地:浙江1楼2016-05-10 17:27回复