gpt4 book ai didi

java - 静态 block 中thread.join()引起的死锁

转载 作者:行者123 更新时间:2023-11-29 08:49:49 26 4
gpt4 key购买 nike

我遇到了一个死锁场景,可以概括为如下所示的 StaticDeadlock 类。

这个简单的程序将卡住在 o.getClass()。这是我对发生的事情的猜测,但有人能更好地解释一下吗?

1)程序进入StaticDeadlock静态 block

2) 线程开始

3) main thread 等待thread 完成,因此无法完成静态 block

4) 在 thread 内部它访问 StaticDeadlock.o 但 StaticDeadlock 的静态 block 还没有完成。因此程序卡住了?

    public class StaticDeadlock
{
private static final Object o = new Object();

static {
MyThread thread = new MyThread();
thread.start();

try {
thread.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}

public static void main (String[] args)
{
System.out.println("all is well.");
}

static class MyThread extends Thread
{
@Override
public void run ()
{
System.out.println("inside mythread");
o.getClass();
}
}

}

最佳答案

是的,差不多就是这样。新线程正在等待 StaticDeadlock 的类初始值设定项完成,然后才能访问静态成员。参见 section 12.4.2 of the Java Language Specification有关详细信息,特别是这些步骤:

  1. Synchronize (§14.19) on the Class object that represents the class or interface to be initialized. This involves waiting until the current thread can obtain the lock for that object (§17.1).

  2. If initialization is in progress for the class or interface by some other thread, then wait on this Class object (which temporarily releases the lock). When the current thread awakens from the wait, repeat this step.

  3. If initialization is in progress for the class or interface by the current thread, then this must be a recursive request for initialization. Release the lock on the Class object and complete normally.

  4. If the class or interface has already been initialized, then no further action is required. Release the lock on the Class object and complete normally.

它甚至不会通过第二个线程中的第 1 步,因为第一个线程拥有锁并且不会释放它。

请注意,它不会调用导致问题的 getClass() - 执行需要 o 的值的任何都会产生第二个线程等到类初始化程序完成,这当然不会发生,因为第一个线程正在等待第二个线程完成。

关于java - 静态 block 中thread.join()引起的死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23338841/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com