gpt4 book ai didi

java - 使用 volatile 变量停止线程

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

基本上,如果我删除不必要的东西,我就会得到以下代码:

public class Foo {
private volatile boolean isFinished = false;
private long timeOut = 60 * 1000;
...

// Called asynchronously from another thread
public setFinished(boolean value) {
isFinished = value;
}

public wait() {
...
long start = SystemClock.uptimeMillis();
while(!isFinished && (SystemClock.uptimeMillis() - start) <= timeOut) {
...
}

if (isFinished) {
// Log success!!!
...
}
else {
// Log time out!!!
...
}
}
}

这段代码在 95% 的情况下都能工作。日志文件类似于:

`wait()` is called waiting starts
`setFinished(true)` is called
`setFinished(true)` returns
"success" entry in the log

但有时,根据日志文件会发生以下情况:

`wait()` is called waiting starts
`setFinished(true)` is called
`setFinished(true)` returns
about 60 seconds pass
"time out" entry in the log

有什么想法吗?

最佳答案

我唯一的猜测是这三个点内有一些东西阻止了循环执行:

while(!isFinished && (SystemClock.uptimeMillis() - start) <= timeOut) {
...
}

更新:您也可以尝试使用 System.currentTimeMillis(),因为 uptimeMillis() 时钟可能会因环境变化而停止。

关于java - 使用 volatile 变量停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20655090/

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