繁体   English   中英

使用volatile变量停止线程

[英]Thread stopping using volatile variable

基本上,如果我删除了不必要的内容,我会得到以下代码:

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()时钟可能会停止。

如果isFinished仅从false转换为true,并且如果while循环已退出,则isFinished必须为true。

即使您没有指定volatile (在实践中)也是如此,并且在您指定了volatile (在理论上和实践上)的情况下,也肯定是这种情况。

因此,我的猜测是第一个假设是错误的。 如果我是你,我将尝试以下方法:

// Called asynchronously from another thread
public setFinished(boolean value) {
    if(!value){
        throw new AssertionError("huh?");
    }
    isFinished = value;
}

看看会发生什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM