Java-Thread.join()不会释放锁 [英] Java - Thread.join( ) does not release the lock

查看:506
本文介绍了Java-Thread.join()不会释放锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我调试了这段代码,但我不明白为什么会出现死锁.当您执行此代码时,它看起来像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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆