-
多线程产生死锁的原因:
① 多个线程对多个资源进行访问
② 对资源访问的顺序不对 -
举例说明
public class UseThreadDeadLock { private static Object obj1 = new Object(); // 代表对象1 private static Object obj2 = new Object(); // 代表对象2 private static void methodForMainThread() { String threadName = Thread.currentThread().getName(); synchronized (obj1) { System.out.println(threadName + ": obj1 is used"); synchronized (obj2) { System.out.println(threadName + ": obj2 is used"); } } } private static void methodForChildThread() { String threadName = Thread.currentThread().getName(); synchronized (obj2) { System.out.println(threadName + ": obj2 is used"); synchronized (obj1) { System.out.println(threadName + ": obj1 is used"); } } } static class FruitThread extends Thread { @Override public void run() { super.run(); methodForChildThread(); } } public static void main(String[] args) { FruitThread fruitThread = new FruitThread(); fruitThread.start(); methodForMainThread(); } }
-
运行结果如下:
总结: 通过运行结果可以看出来是主线程先拿到了 obj1,所以子线程拿不到 obj1; 同样因为子线程拿到了 obj2, 而主线程就拿不到,这样访问资源的顺序不对,就产生了死锁。