java死锁

来源:互联网 发布:兰黛丽莎香水知乎 编辑:程序博客网 时间:2024/06/05 13:33
//死锁情况 
/**
两个锁的相互嵌套。
两个线程分别进行。
*/
class Test implements Runnable
{
private boolean flag;
Test(boolean flag)
{
this.flag = flag;
}


public void run()
{
if (flag)
{
synchronized(MyLock.locka)
{
System.out.println(Thread.currentThread().getName()+"...if locka");
synchronized (MyLock.lockb)
{
System.out.println(Thread.currentThread().getName()+"...if lockb");
}
}
}
else 
{
synchronized(MyLock.lockb)
{
System.out.println(Thread.currentThread().getName()+"...else locka");
synchronized (MyLock.locka)
{
System.out.println(Thread.currentThread().getName()+"...else lockb");
}
}
}
}


}


class MyLock
{
public static final Object locka = new Object();
public static final Object lockb = new Object();


}


class DeadLockDemo 
{
public static void main(String[] args) 
{
Test a1 = new Test(true);
Test a2 = new Test(false);
Thread t1 = new Thread(a1);
Thread t2 = new Thread(a2);


t1.start();
t2.start();
}
}
0 0
原创粉丝点击