class MyLock
{ //创建了两个锁对象,只要是个对象就可以做锁,这里创建了两个object对象
static Object locka = new Object();
static Object lockb = new Object();
}
class Test implements Runnable
{
//构造方法里面就需要传入一个falg boolean标记
private boolean flag;
Test(boolean flag)
{
this.flag = flag;
}
public void run()
{
if (flag) //假如标记为真,进来
{
while(true)
{
synchronized (MyLock.locka) //上第一个锁对象
{
System.out.println("......if locka ");
synchronized (MyLock.lockb) //上第二个锁对象
{
System.out.println(".......if lockb");
}
}
}
}
else//假如标记为假,
{
while (true)
{
synchronized (MyLock.lockb) //上第二个锁对象
{
System.out.println("......else lockb");
synchronized(MyLock.locka) //上第一个锁对象
{
System.out.println(".....else locka");
}
}
}
}
}
}
public 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();
}
} |