gpt4 book ai didi

java - 等待超时

转载 作者:行者123 更新时间:2023-11-30 04:34:57 24 4
gpt4 key购买 nike

如果我这样做

synchronization (someobject) {  
while (someobject.need2wait()) {
someobject.wait(timeout);
}
}

超时到期后会发生什么?如果另一个线程已锁定 someobject会被中断吗?

最佳答案

答案就在文档中。您可以使用以下代码亲自尝试 - 您会发现没有线程被中断:

public class TestWait {
private static volatile boolean ready = false;

public static void main(String[] args) throws Exception {
final Object lock = new Object();
Runnable waitingTask = new Runnable() {

@Override
public void run() {
synchronized(lock) {
while(!ready) {
try {
System.out.println("Going to wait here");
lock.wait(1000);
} catch (InterruptedException ex) {
System.out.println("Thread interrupted");
}
}
System.out.println("I'm done waiting");
}
}
};
new Thread(waitingTask).start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
System.out.println("main interrupted");
}
ready = true;
System.out.println("ready");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
System.out.println("main interrupted");
}
}
}

关于java - 等待超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13722300/

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