简体   繁体   中英

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.

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. 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 .

(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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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