为什么这段代码会产生死锁? [英] why does this code produce deadlock?
问题描述
class A {
static final int i;
static {
i = 128;
Thread t = new Thread() {
public void run() {
System.out.println("i=" + i);
}
};
t.start();
try {
t.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public class MainTesting {
public static void main(String[] args) {
A a = new A();
System.out.println("finish");
}
}
我永远不会得到finish
得到打印并得到i的值.
为什么会这样?
I never get finish
get printed and value of i.
Why is it so?
推荐答案
您从线程1(主"线程)开始,并开始为A
类执行静态初始化程序.
You start off on thread 1 (the "main" thread), and start executing the static initializer for the A
class.
然后在该静态初始化程序中启动一个新线程(2),该线程使用A
类中的某些内容.这意味着根据
Within that static initializer, you then start a new thread (2), which uses something within the A
class. That means that thread 2 needs to wait until the A
class has finished initilaizing before it will proceed, as per section 12.4.2 of the JLS:
如果C的Class对象指示其他线程正在对C进行初始化,则释放LC并阻塞当前线程,直到得知正在进行的初始化已完成,然后重复此步骤.
If the Class object for C indicates that initialization is in progress for C by some other thread, then release LC and block the current thread until informed that the in-progress initialization has completed, at which time repeat this step.
但是,A
的静态初始化程序要等到 完成之前,直到线程2完成(通过调用join()
),这会导致死锁:静态初始化程序要等到线程2才能完成已经完成,线程2在静态初始化程序完成之前无法完成...
However, your static initializer for A
waits until thread 2 has completed (by calling join()
) before it completes, leading to deadlock: the static initializer can't complete until thread 2 has completed, and thread 2 can't complete until the static initializer has completed...
结果:不要这样做:)
这篇关于为什么这段代码会产生死锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!