线程死锁:是指两个或是两个以上的线程在执行过程中,由于竞争资源或是由于通信造成的一种阻塞现象。若无外力作用,他们将一直运行下去。此时称系统产生了死锁或是系统处于死锁状态。这些永远在等待的线程,称为死锁线程。
例如:一位老大爷去买水果,付账时说:我要先吃完,才可以付账。但是水果店的老板说:你要先付帐,才可以吃水果。于是两人僵持下去。永远也无法完成交易,一直僵持下去,造成死锁!
线程死锁的案例:
八戒买悟空的桃,需要先要桃,再给钱。悟空需要先拿到钱,再给桃。
创建钱、桃、悟空、八戒类,买的线程和卖的线程。
1.桃类:Peach.java
public class Peach {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2.钱类:Money.java
public class Money {
}
3.悟空类
public class WuKong {
Peach peach;
public Peach getPeach() {
return peach;
}
public void setPeach(Peach peach) {
this.peach = peach;
}
}
4.八戒类
public class BaJie {
Money money;
public Money getMoney() {
return money;
}
public void setMoney(Money money) {
this.money = money;
}
}
5.买的线程
public class BuyThread extends Thread{
//同步对象
private BaJie bajie;
private WuKong wukong;
public BuyThread(BaJie bajie, WuKong wukong) {
this.bajie = bajie;
this.wukong = wukong;
}
@Override
public void run() {
//获取八戒的钱上锁
synchronized (bajie.getMoney()) {
System.out.println("八戒有钱,但是想要先拿到桃!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (wukong.getPeach()) {
System.out.println("八戒拿到了桃!");
}
}
}
}
6.卖的线程
public class SellThread extends Thread{
//同步对象
private BaJie bajie;
private WuKong wukong;
public SellThread(BaJie bajie, WuKong wukong) {
this.bajie = bajie;
this.wukong = wukong;
}
@Override
public void run() {
synchronized (wukong.getPeach()) {
System.out.println("悟空有桃,但是想要先拿到钱!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (bajie.getMoney()) {
System.out.println("悟空拿到了桃!");
}
}
}
}
7.创建测试类
public class test {
public static void main(String args[]){
// 创建八戒和悟空的对象
Peach peach = new Peach();
Money money = new Money();
BaJie bajie = new BaJie();
bajie.setMoney(money);
WuKong wukong = new WuKong();
wukong.setPeach(peach);
// 创建线程对象
BuyThread bt = new BuyThread(bajie, wukong);
bt.start();
SellThread st = new SellThread(bajie, wukong);
st.start();
}
}
线程的死锁过程