我试图在
java中实现死锁.线程t1和t2以相同的顺序锁定s1和s2导致死锁情况.但是,如果我注释掉Line1和Line2调用线程类的sleep方法,则不会发生死锁.我运行此程序超过15次,但删除第1行和第2行不会导致死锁.
所以我的查询是,第1行和第2行(调用Thread.sleep)是死锁所必需的.如果是,那么我还没有理解死锁.如果不是,它会导致其他JVM死锁吗?
//Thread DeadLock
class Threadlock
{
private final static String s1="java";
private final static String s2="deadlock";
public static void main(String[] args)
{
Thread t1= new Thread()
{
public void run()
{
synchronized(s1)
{
try { Thread.sleep(100);}
catch (Exception e) {} //Line 1
synchronized(s2)
{}
}
}
};
Thread t2= new Thread()
{
public void run()
{
synchronized(s2)
{
try { Thread.sleep(100);} catch (Exception e) {} //Line 2
synchronized(s1)
{}
}
}
};
t2.start();
t1.start();
}
}