对于一个多线程程序,如果它的多个线程要使用同一部分资源,我们就可以使用某种加锁机制,比如sycrhronized方法,来防止多个线程同时使用这个资源。但使用加锁机制可能会导致死锁现象:当一个线程在执行某任务是需要等待另一个线程,而后者又要等待其它线程……最后一个线程又要等待第一个线程。这些线程都在等待其它线程释放锁,都没有执行完毕。
下面是一个简单的死锁问题的演示代码。两个类:TestDeadLock和RunnableImpl。TestDeadLock调用main()方法,RunnableImpl实现Runnable类。
TestDeadLock类:
package com.testDeadLock;
/**
* Java 死锁实例
* Created by tbx709 on 2017/4/14.
*/
public class TestDeadLock {
//主方法
public static void main(String[] args) throws InterruptedException {
Object obj1 = new Object();
Object obj2 = new Object();
Thread thread1 = new Thread(new RunnableImpl(obj1, obj2));
Thread thread2 = new Thread(new RunnableImpl(obj2, obj1));
thread1.setName("thread1");
thread2.setName("thread2");
thread1.start();
Thread.sleep(1000);
thread2.start();
}//主方法结束
}
RunnableImpl类:
package com.testDeadLock;
/**
* Java 死锁实例
* Created by tbx709 on 2017/4/14.
*/
public class RunnableImpl implements Runnable {
//声明变量
private Object obj1, obj2;
//构造方法
public RunnableImpl(Object obj1, Object obj2) {
this.obj1 = obj1;
this.obj2 = obj2;
}//构造方法结束
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name + ": " + obj1 + " start");
synchronized(obj1) {
System.out.println(name + ": " + obj1 + " doing");
doing();
System.out.println(name + ": " + obj2 + " start");
synchronized(obj2) {
System.out.println(name + ": " + obj2 + " doing");
doing();
}//inner synchronized() end
System.out.println(name + ": " + obj2 + " over");
}//synchronized() end
System.out.println(name + ": " + obj1 + " over");
}//run() end
private void doing() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}//doing() end
}