首先我们引入一个例子
有这么两个人,一个叫做MyThread1, 一个叫做MyThread2
他们都想要吃饭,但是,只有一双筷子和一碗饭并且它们被放在桌子的最左边和最右边
MyThread1跑向左边,MyThread2跑向右边
假设MyThread1跑的比较快,他抢到了那碗饭,但是由于体力问题,他要休息一秒再去抢筷子
然而就在他休息的时候,MyThread2赶到了筷子那儿,同样由于体力问题,他也要休息一秒
就在这个时候MyThread1休息好了 于是他来到了筷子这儿,发现筷子被MyThread2拿走了
MyThread1要MyThread2 的筷子,MyThread2要MyThread1的饭,他们都不想交出手上的东西结果就悲剧了。。。。。。。
以下是代码的实现:
/**
*
* @author zero
* there is a instance of deadlock
* MyThread1 use synchronized to locked rice, unless he finish his job or he will not give up rice
* MyThread1 take a break for one second after he got the rice
* During this period, MyThread2 use synchronized to locked chopsticks, unless he finish his job or he will not give up chopsticks
* MyThread2 take a break for one second after he got the chopsticks
* During this period,MyThread1 wake up and look for chopsticks, but the chopsticks have taken away by MyThread2
* They all want the other's resource
* So deadlock completed
*/
public class DeadLockInstance {
private static Object rice = new Object();
private static Object chopsticks = new Object();
static class MyThread1 extends Thread {
@Override
public void run() {
synchronized (rice) {
try {
Thread.sleep(1000);
synchronized (chopsticks) {
System.out.println("MyThread1 can eat rice now!");
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
static class MyThread2 extends Thread {
@Override
public void run() {
synchronized (chopsticks) {
try {
Thread.sleep(1000);
synchronized (rice) {
System.out.println("MyThread2 can eat rice now!");
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new MyThread1().start();
new MyThread2().start();
}
}
一般造成死锁必须同时满足如下4个条件:
互斥条件线程使用的资源必须至少有一个是不能共享的,(饭和筷子都只有数量1,只能轮流使用,不能共享)
至少有一个线程必须持有一个资源并且正在等待获取一个当前被其他线程持有的资源。(有饭的求筷子,有筷子的求饭)
分配的资源不能从相应的线程中被强制剥夺。(谁也抢不过谁)
循环等待条件
第一个线程等待其他线程,后者又在等待第一个线程。(有饭的求筷子,有筷子的求饭)
死锁的解决方式请参照下一篇文章