gpt4 book ai didi

java - 调用中断后锁释放

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

我在下面的线程中尝试复制中断功能

线程 T1

public void run() {
synchronized (i) {

Thread.currentThread().interrupt();

try {
i.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Inside r1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

线程 T2

public void run() {
synchronized (i) {
System.out.println("Inside r2");

}

}

当我运行上述 2 个线程时,我得到以下输出

java.lang.InterruptedException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Unknown Source)
at InterruptTest$1.run(InterruptTest.java:17)
at java.lang.Thread.run(Unknown Source)
Inside r1
Inside r2

我的问题是,在T1中的wait()之后,锁被释放。那么“Inside r1”语句在没有被T1加锁的情况下是如何执行的呢?

最佳答案

此时

System.out.println("Inside r1");

执行完毕,线程拥有锁。

Object#wait method 的文档说:

The thread T is then removed from the wait set for this object and re-enabled for thread scheduling. It competes in the usual manner with other threads for the right to synchronize on the object; once it has regained control of the object, all its synchronization claims on the object are restored to the status quo ante - that is, to the situation as of the time that the wait method was invoked. Thread T then returns from the invocation of the wait method. Thus, on return from the wait method, the synchronization state of the object and of thread T is exactly as it was when the wait method was invoked.

当线程进入wait方法时,它放弃对锁(i的监视器)的声明。

当 hibernate 时,线程仍处于等待方法中。

为了让线程退出该方法,它必须重新获取 i 上的锁。

因此,如果一个线程要离开等待方法(无论是由于被通知、中断还是被虚假唤醒),它必须取回锁才能退出等待方法。

没有条件变量可以在 wait 调用周围的 while 循环中进行测试,并且对变量名称的可疑选择 i(对于整数?你是否正在改变这个??),让我认为还有其他问题.

关于java - 调用中断后锁释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59930451/

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