Java-Thread.join()不会释放锁 [英] Java - Thread.join( ) does not release the lock
问题描述
我调试了这段代码,但我不明白为什么会出现死锁.当您执行此代码时,它看起来像join方法中的主线程锁,而另一个线程正在等待获取锁.
i debug this code and i don't understand why i get deadlock. When you execute this code, it looks like the main thread lock in the join method while the other thread is waiting to acquire the lock.
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
上.
That's because Thread.join()
doesn't release any locks. You've designed a perfectly working deadlock, where Thread-1
is waiting for Thread-2
to die having locked on Foo
, and Thread-2
is waiting to lock on Foo
.
(从技术上讲,当前实现确实释放了锁,因为它在Thread
上同步时在内部使用wait()
.但这是一种与用户代码无关的内部机制)
(Technically speaking the current implementation does release locks, as it uses internally wait()
while synchronized on Thread
. However that's an internal mechanism not related to user code)
这篇关于Java-Thread.join()不会释放锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!