要素:两个线程、两把锁、两组嵌套的同步代码块。
下面就用买卖场景来模拟线程死锁。
package com.zzj.thread;
/**
* 线程死锁
*
* @author Administrator
*
*/
public class DeathThread {
public static void main(String[] args) {
Object money = new Object();
Object goods = new Object();
new Thread(new Money(money, goods)).start();
new Thread(new Goods(money, goods)).start();
}
}
/**
* 买者
*
* @author Administrator
*
*/
class Money implements Runnable {
private Object money;
private Object goods;
public Money(Object money, Object goods) {
this.money = money;
this.goods = goods;
}
@Override
public void run() {
synchronized (money) {
System.out.println("买者思索中......");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("买者说:先给货,再交钱!");
synchronized (goods) {
System.out.println("买者拿到货物......");
}
}
}
}
/**
* 卖者
*
* @author Administrator
*
*/
class Goods implements Runnable {
private Object money;
private Object goods;
public Goods(Object money, Object goods) {
this.money = money;
this.goods = goods;
}
@Override
public void run() {
synchronized (goods) {
System.out.println("卖者思索中......");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("卖者说:先交钱,再给货!");
synchronized (money) {
System.out.println("卖者拿到钱......");
}
}
}
}
输出结果:
买者思索中......
卖者思索中......
买者说:先给货,再交钱!
卖者说:先交钱,再给货!
结果是买者拿不到货,卖者也拿不到钱。