按着视频来写的,只是把锁这个类的成员换成非静态了
class Lock
{
Object obj1=new Object(); //非静态的锁
Object obj2=new Object();
}
class Test1 implements Runnable
{
private boolean flag;
Test1(boolean flag)
{
this.flag=flag;
}
Lock l=new Lock(); //创建对象来调用里面的成员作为锁
public void run()
{
for(int x=1; x<100; x++)
{
if(flag)
{
synchronized(l.obj1)
{
System.out.println(Thread.currentThread().getName()+" if obj1");
synchronized(l.obj2)
{
System.out.println(Thread.currentThread().getName()+" if obj2");
}
}
}
else
{
synchronized(l.obj2)
{
System.out.println(Thread.currentThread().getName()+" else obj2");
synchronized(l.obj1)
{
System.out.println(Thread.currentThread().getName()+" else obj1");
}
}
}
}
}
}
public class DeadLockDemo
{
public static void main(String[] args)
{
new Thread(new Test1(true)).start();
new Thread(new Test1(false)).start();
}
}
|