背景:
多线程产生死锁的条件之一: 对资源访问的顺序不对,所以可以通过对资源的有序访问来避免死锁的产生。
-
示例代码
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() { Thread childThread = Thread.currentThread(); childThread.setName("子线程"); String threadName = Thread.currentThread().getName(); synchronized (obj1) { System.out.println(threadName + ": obj2 is used"); synchronized (obj2) { 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) { Thread.currentThread().setName("主线程"); FruitThread fruitThread = new FruitThread(); fruitThread.start(); methodForMainThread(); } }
-
运行结果:
总结: 所以可以看到主线程和子线程都按照访问obj1和obj2的顺序就不会产生死锁了。