* 死锁的原因是由于 两个线程相互等待 对方已被锁定的资源
形象比喻:死锁
|-- 多个线程,你抢我的锁,我抢你的锁
|-- 你中有我,我中有你
|-- 同步的嵌套
举例 A 线程 B线程
A持有A锁,然后,运行,A持有了B锁
B持有B锁,运行,B持有A锁
下面示例展示:
/*
死锁实例
*/
class Dead implements Runnable
{
private boolean b = false;
Dead(boolean b)
{
this.b = b;
}
public void run()
{
while(true)
{
if(b)
{
synchronized(Locks.locka)
{//0线程,进来后,只有了A锁,打印了if,CPU走了
System.out.println(Thread.currentThread().getName()+" locka...+.. if");
synchronized(Locks.lockb)
{
System.out.println(Thread.currentThread().getName()+" lockb...+.. if");
}
}
}
else
{
synchronized(Locks.lockb)
{
//1线程就进来了,持有了B锁,打印了else
System.out.println(Thread.currentThread().getName()+" lockb...+.. else");
synchronized(Locks.locka)
{
System.out.println(Thread.currentThread().getName()+" locka...+.. else");
}
}
}
}
}
}
//创造锁
class Locks
{
public static Object locka = new Object();
public static Object lockb = new Object();
}
class DeadLock
{
public static void main(String[] args)
{
Dead d1 = new Dead(true);
Dead d2 = new Dead(false);
Thread t1 = new Thread(d1);
Thread t2 = new Thread(d2);
t1.start();
t2.start();
}
}