class Test implements Runnable
{
static Object o1=new Object(),  o2=new Object();
int i=1;
public void run()
{
System.out.println("i="+i);
if(i==1)
{
synchronized(o1)
{
try
{
Thread.sleep(500);
}
catch (Exception e)
{

}
}
synchronized(o2)
{

System.out.println("o1 is finish");
}
}
if(i==0)
{

synchronized(o2)
{

try
{
Thread.sleep(500);
}
catch(Exception e)
{

}
}
synchronized(o1)
{

System.out.println("2");
}
}
}
}
public class ThreadDeadTest
{
public static void main(String [] args)
{
Test t1=new Test();
Test t2=new Test();
t1.i=1;
t2.i=0;
Thread th1=new Thread(t1);
Thread th2=new Thread(t2);
th1.start();
th2.start();
}
}
为什么我的这个程序造不成死锁现象。问题出在哪里?

解决方案 »

  1.   

    死锁的是四要素
    1.互斥条件,任务使用的资源至少有一个是不能共享的。
    2.至少有一个任务它必须持有一个资源且正在等待获取一个当前被识别的任务持有的资源。
    3.资源不能被任务抢占,任务必须把资源释放当作普通事件。
    4.必须有循环等待,一个任务等待其他任务所持有的资源。上面这些引自thinking java
    大学操作系统教材里面也是这么说地,你百度一下“哲学家就餐问题”