[code="java"]
public class DeadLockTest implements Runnable
{
private int flag = 1;
protected Object o1 = new Object();
protected Object o2 = new Object();
/**
* run方法
*/
@Override
public void run()
{
System.out.println("flag = " + flag);
if(flag == 1)
{
synchronized (o1)
{
try
{
System.out.println("o1 is locked");
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("release o1");
synchronized (o2)
{
System.out.println("1");
}
}
if(flag == 0)
{
synchronized (o2)
{
try
{
System.out.println("o2 is locked");
Thread.sleep(1000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("release o2");
synchronized (o1)
{
System.out.println("0");
}
}
}
/**
* main函数
* @author kf56385
* @param args
*/
public static void main(String[] args)
{
DeadLockTest d1 = new DeadLockTest();
d1.flag = 1;
DeadLockTest d2 = new DeadLockTest();
d2.flag = 0;
Thread t1 = new Thread(d1);
Thread t2 = new Thread(d2);
t1.start();
t2.start();
}
[/code]
按照网上写的例子,可是运行时并没有发生死锁,以下是控制台输出:
flag = 1
o1 is locked
flag = 0
o2 is locked
release o1
1
release o2
0
很奇怪,在release o1之后,要输出"1"这个值的时候 o2还是被锁住的。怎么还会有输出呢?望指教