死锁
小刘、小王在玩手机。小刘在用自己的手机打游戏,同时又想抢小王的手机看电视。这会小王正在拿自己手机打游戏,小王也想拿小刘的的手机看电视。小刘拿不到小王的手机,因为小王在打游戏,抢不走,所以小刘在打游戏的时候也在等待小王手机空闲下来。小王正在打游戏,小王也想拿小刘的手机看电视,但是这会小刘正在用着手机打游戏,所以小王抢不走。小刘的要求是,自己在玩手机的时候,还要拿小王的手机看电视。而小王的要求是,自己在玩手机的时候,要抢小刘的手机看电视。也就是说,小刘永远都等不到小王的手机,因为小王得不到小刘的手机,小王就永远不会停止,小王不会停止,小刘就会一直等待小王的手机,而小王也会一直等待小刘的手机,等啊等,等到死翘翘!
案例
线程1启动,加锁占用了亚瑟,同时还想着独自占用鲁班;线程2启动,加锁占用了鲁班,同时还想着独自占用妲己;线程3启动,加锁占用了妲己,同时还想着独自占用亚瑟;形成闭环,死锁后不能停止。

代码
package com.thread.thread14;
import com.thread.Hero;
public class TestThread {
public static void main(String[] args) {
final Hero yase = new Hero();
yase.name = "亚瑟";
final Hero luban = new Hero();
luban.name = "鲁班";
final Hero daji = new Hero();
daji.name = "妲己";
Thread t1 = new Thread() {
public void run() { //线程执行
//占有亚瑟
synchronized (yase) { //这里就占有了亚瑟
System.out.println("t1已经占有亚瑟");
try{
//停顿1000毫秒 另一个线程有时间占领亚瑟
因为我要用两个线程来看效果 一个已经占有了亚瑟 另一个准备来抢亚瑟 所以 不能让这个线程执行很快就结束
//我要留一点时间 等t1线程在占有时候 等t2过来抢
Thread.sleep(2000);
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("t1试图占有鲁班");
System.out.println("t1等待中");
synchronized(luban) { //在占有亚瑟的同时 还要去抢鲁班 霸道
System.out.println("t1已经占有鲁班");
}
}
}
};
t1.start(); //启动t1线程
Thread t2 = new Thread(){
public void run() {
//正在占有鲁班
synchronized(luban) {
System.out.println("t2已经占有鲁班");
try{
//让这个线程运行的久一点 希望等的时间够久 让别个有时间来抢它的鲁班
Thread.sleep(2000);
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t2试图占有妲己");
System.out.println("t2等待中");
synchronized (daji) {
System.out.println("t2已经占有妲己");
}
}
}
};
t2.start();
Thread t3 = new Thread(){
public void run() {
//正在占有妲己
synchronized(daji) {
System.out.println("t3已经占用了妲己");
try{
//让这个线程运行的久一点 希望等的时间够久 让别个有时间来抢它的鲁班
Thread.sleep(2000);
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t3试图占有亚瑟");
System.out.println("t3等待中");
synchronized (yase) {
System.out.println("t3已经占有亚瑟");
}
}
}
};
t3.start();
}
}
效果
