gpt4 book ai didi

java - 线程何时释放对象上的锁?

转载 作者:行者123 更新时间:2023-12-01 22:04:12 25 4
gpt4 key购买 nike

我是多线程新手。目前我正在学习锁定、通知和同步块(synchronized block)。我创建了一个小程序来检查等待和通知如何使用同步块(synchronized block),如果我不会创建任何线程(我认为主线程将获得锁)。下面是为了更好地理解的代码。

public class Problem1 
{
public void waitForSignal() throws InterruptedException
{
Object obj=new Object();
synchronized (obj) {
obj.wait();
obj.notify();
}
}
public static void main(String args[]) throws InterruptedException
{
Problem1 pb=new Problem1();
pb.waitForSignal();
System.out.println("hello");//controll not come here
}

}

如果我运行上面的程序,它就会卡住。并且控制既不会转到notify(),也不会退出同步块(synchronized block)。为什么代码会这样。我尝试在谷歌上搜索,发现了以下声明

wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ).

我从上面的陈述中了解到,为了正确执行我的程序,我必须创建另一个线程,它将进入同一个监视器并中断当前持有锁的线程的执行。如果我错了,请纠正我。请我更正上面的代码,这样它就能正常工作而不会卡住。

最佳答案

当您调用wait时,其他线程将必须获取obj上的锁并调用notifynotifyAll 向等待线程发出信号以继续。最简单的理解方法是在消费者/生产者问题的背景下,Oracle 有一个关于 that 的非常好的教程。 .

线程中断是完全不同的事情。它是对被中断线程检查其中断状态并终止处理的请求。 Brian Goetz 在 properly handling InterruptedException 的背景下有一篇关于此的很棒的文章。 .

关于java - 线程何时释放对象上的锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33088039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com