Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 检查线程是否处于睡眠状态总是返回true_Java_Multithreading - Fatal编程技术网

Java 检查线程是否处于睡眠状态总是返回true

Java 检查线程是否处于睡眠状态总是返回true,java,multithreading,Java,Multithreading,我目前有以下问题: 我制作了一个“缓存更新程序线程”,它检查更新,然后休眠一段时间。我还构建了一个按钮,使用户可以手动检查更新。线程是这样构建的: public static Thread cacheUpdater = new Thread(new Runnable() { int milliSecondSleepTime = 10000; public void run() { try { cacheUpdater.setPriori

我目前有以下问题:

我制作了一个“缓存更新程序线程”,它检查更新,然后休眠一段时间。我还构建了一个
按钮
,使用户可以手动检查更新。
线程
是这样构建的:

public static Thread cacheUpdater = new Thread(new Runnable() {

    int milliSecondSleepTime = 10000;
    public void run() {

        try {
            cacheUpdater.setPriority(Thread.MIN_PRIORITY);

            //Infinite loop
            while (!terminate) {

                        syncStatus.set(0);

                //Check for updates with some methods, not important here.

                syncStatus.set(1);
                Thread.sleep(this.milliSecondSleepTime);
            }
        }
        catch (InterruptedException e) {
            //First check if it is termination time
            if (!terminate) {
                syncStatus.set(0);
                this.run();
            }
        }
        catch (Exception e) {
            System.out.println(e);
        }

        return;
    }

});
如果用户单击手动更新按钮,将运行以下代码:

@FXML public void syncOnRequest() {

    //Only call interrupt, because then it will start again when terminate is still false
    CacheManager.cacheUpdater.interrupt();
    System.out.println(CacheManager.cacheUpdater.getState().equals(State.TIMED_WAITING));

    while (!CacheManager.cacheUpdater.getState().equals(State.TIMED_WAITING)) {
        //LOOP FOREVER
    }

    //Some code that needs to be executed after the cache is updated

}
当缓存更新程序准备好手动更新时,我想继续执行
syncOnRequest()
方法中的代码。我想检查它是否正在睡眠,但这不起作用,因为
System.out.println()
立即返回true。我测量了更新所需的时间,它在200到400毫秒之间

我做错了什么?为什么它总是返回真值?

附加问题:有时单击按钮会杀死
线程
,因为它刚刚醒来。不会引发中断异常

我如何确保
线程在这种情况下也将重新启动?

请注意
线程#中断()
是要求线程中断自身的唯一礼貌方式(除非您明确实现另一种方式)。因此,使用它重新启动检查是一种不好的做法。为了同步目的检查线程状态,并向外部客户端公开使缓存保持最新的线程也是如此

您的管理器应该有一个
updateCache()
方法,您将直接从UI代码调用,自动更新线程将定期调用相同的方法*。在该方法中,确保对缓存数据的访问是正确同步的,或者是以原子方式进行的

<>)不使用自己的周期线程,而是考虑使用
类以及使其成为守护进程线程。

我不完全确定您希望在这里做什么。但是也许考虑使用“等待”代替睡眠,这样当你希望它恢复处理时,你可以“通知”线程。