public class TestDeadLock implements Runnable
{
public int flag=1;
static Object o1=new Object();
static Object o2=new Object();public void run()
{
if(flag==1){
synchronized (o1){
try
{
Thread.sleep(100);
}
catch(Exception e){}
}
synchronized (o2)
{
System.out.println("flag==1");
}
} if(flag==0){
synchronized (o2)
{
try{
Thread.sleep(100);
}
catch(Exception e)
{}
}
synchronized (o1){
System.out.println("flag==2");
}
}
}
public static void main(String[] args)
{
TestDeadLock te1=new TestDeadLock();
TestDeadLock te2=new TestDeadLock();
te1.flag=1;
te2.flag=0;
Thread t1 = new Thread(te1);
Thread t2 = new Thread(te2);
t1.start();
t2.start();
}
}
我是这么想的:t1线程先启动因为flag==1所以应该先锁住o1,睡眠。然后t2启动flag==2锁住o2,然后t1醒来,但o2被锁定。所以无法进入下面被锁定的代码块。同理t2也无法继续进行。
但我试着怎么最后可以打印出结果:flag==1
flag==2
{
public int flag=1;
static Object o1=new Object();
static Object o2=new Object();public void run()
{
if(flag==1){
synchronized (o1){
try
{
Thread.sleep(100);
}
catch(Exception e){}
}
synchronized (o2)
{
System.out.println("flag==1");
}
} if(flag==0){
synchronized (o2)
{
try{
Thread.sleep(100);
}
catch(Exception e)
{}
}
synchronized (o1){
System.out.println("flag==2");
}
}
}
public static void main(String[] args)
{
TestDeadLock te1=new TestDeadLock();
TestDeadLock te2=new TestDeadLock();
te1.flag=1;
te2.flag=0;
Thread t1 = new Thread(te1);
Thread t2 = new Thread(te2);
t1.start();
t2.start();
}
}
我是这么想的:t1线程先启动因为flag==1所以应该先锁住o1,睡眠。然后t2启动flag==2锁住o2,然后t1醒来,但o2被锁定。所以无法进入下面被锁定的代码块。同理t2也无法继续进行。
但我试着怎么最后可以打印出结果:flag==1
flag==2
synchronized (o2){ synchronized (o2){ }}这样才可以