[英]Java - Thread.join( ) does not release the lock
我调试了这段代码,但我不明白为什么会出现死锁。 当你执行这段代码时,它看起来像join方法中的主线程锁,而另一个线程正在等待获取锁。
public class Foo {
private final Thread thread;
public Foo() {
thread = new Thread(new Bar(), "F");
thread.start();
}
public void run() {
synchronized (this) {
thread.interrupt();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Foo run method");
}
}
private final class Bar implements Runnable {
@Override
public void run() {
synchronized (Foo.this) {
System.out.println("Bar run method");
}
}
}
public static void main(String[] args) throws InterruptedException {
final Foo foo = new Foo();
foo.run();
}
}
谢谢你的帮助!
那是因为Thread.join()
不会释放任何锁。 您已经设计了一个完美工作的死锁,其中Thread-1
正在等待Thread-2
在锁定Foo
死亡,而Thread-2
正在等待锁定在Foo
。
(从技术上讲,当前的实现确实会释放锁,因为它在Thread
同步时在内部使用wait()
。但这是一种与用户代码无关的内部机制)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.