死锁:同步中嵌套同步。
class Test implements Runnable//多线程的表现形式
{
private boolean flag;//定义一个标志
Test(boolean flag)//构造函数
{
this.flag=flag;
}
public void run()//定义run方法
{
while(true)
{
if(flag){
synchronized(MyLock.locka)
{
synchronized(MyLock.lockb)
{
System.out.println(" if lockb");
}
}
}
else
{
while(true)
{
if(flag){
synchronized(MyLock.lockb)
{
synchronized(MyLock.locka)
{
System.out.println(" if locka");
}
}
}
}
}
}
}
class MyLock
{
static Object locka=new Object();
static Object lockb=new Object();
}
class DeadLockTest{
public static void main(String[] args)
{
Thread t1=new Thread(new Test(true));
Thread t2=new Thread(new Test(false));
t1.start();
t2.start();
}
}