简体   繁体   English

Java - Thread.join() 不释放锁

[英]Java - Thread.join( ) does not release the lock

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.当你执行这段代码时,它看起来像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();
}

}

Thanks for your help!谢谢你的帮助!

That's because Thread.join() doesn't release any locks.那是因为Thread.join()不会释放任何锁。 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-1正在等待Thread-2在锁定Foo死亡,而Thread-2正在等待锁定在Foo

(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) (从技术上讲,当前的实现确实会释放锁,因为它在Thread同步时在内部使用wait() 。但这是一种与用户代码无关的内部机制)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM