首页 > 解决方案 > 在 java 中,这种死锁是否仅在同步块的情况下发生,而不是在同步方法的情况下发生?

问题描述

许多教程显示了死锁的代码,例如,

public class ResolveDeadLockTest {

    public static void main(String[] args) {
        ResolveDeadLockTest test = new ResolveDeadLockTest();

        final A a = test.new A();
        final B b = test.new B();

        // Thread-1
        Runnable block1 = new Runnable() {
            public void run() {
                synchronized (a) {
                    try {
                        // Adding delay so that both threads can start trying to
                        // lock resources
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // Thread-1 have A but need B also
                    synchronized (b) {
                        System.out.println("In block 1");
                    }
                }
            }
        };

        // Thread-2
        Runnable block2 = new Runnable() {
            public void run() {
                synchronized (b) {
                    // Thread-2 have B but need A also
                    synchronized (a) {
                        System.out.println("In block 2");
                    }
                }
            }
        };

        new Thread(block1).start();
        new Thread(block2).start();
    }
}

所以如果我们在那些锁定对象中使用 Synchronized 方法而不是这个类中的 Synchronized 块,那么死锁不会发生吗?

标签: javamultithreadingconcurrency

解决方案


推荐阅读