Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/378.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中的无限循环_Java_While Loop_Threadpool_Infinite Loop_Threadpoolexecutor - Fatal编程技术网

停止线程池Java中的无限循环

停止线程池Java中的无限循环,java,while-loop,threadpool,infinite-loop,threadpoolexecutor,Java,While Loop,Threadpool,Infinite Loop,Threadpoolexecutor,我有以下代码: ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Boolean> f = executor.submit(() -> { if (true) { while (true); } return false; }); try { System.out.println(f.get(10, TimeUnit.MILLISECOND

我有以下代码:

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Boolean> f = executor.submit(() -> {
    if (true) {
        while (true);
    }
    return false;
});
try {
    System.out.println(f.get(10, TimeUnit.MILLISECONDS));
}
catch (InterruptedException | ExecutionException | TimeoutException e) {
    throw e;
}
ExecutorService executor=Executors.newSingleThreadExecutor();
未来f=执行人提交(()->{
如果(真){
虽然(正确);
}
返回false;
});
试一试{
System.out.println(f.get(10,TimeUnit.ms));
}
捕获(InterruptedException | ExecutionException | TimeoutException e){
投掷e;
}
当我运行程序时,我会像应该的那样得到异常,但是While循环会继续运行,程序不会停止。
我尝试了
executor.shutdown()
executor.shutdownow()
f.cancel(true)
等等。

有人知道吗?我花了三天时间试图解决这个问题。

您不应该使用忙循环,但如果线程被中断,您可以停止:

while (!Thread.interrupted()) {
    // do something
}
线程应该等待信号或事件,而不是使用忙循环。甚至在设定的时间间隔内进行轮询。您描述的繁忙循环只会耗尽CPU

例如,您可以简单地调用任何对象,您的线程将在被中断时被唤醒

try {
    (new Object()).wait();
} catch (InterruptedException e) {
    // Interrupted
}

有关线程信号的讨论,请参见此处:

您不应该使用忙循环,但如果线程被中断,您可以停止:

while (!Thread.interrupted()) {
    // do something
}
线程应该等待信号或事件,而不是使用忙循环。甚至在设定的时间间隔内进行轮询。您描述的繁忙循环只会耗尽CPU

例如,您可以简单地调用任何对象,您的线程将在被中断时被唤醒

try {
    (new Object()).wait();
} catch (InterruptedException e) {
    // Interrupted
}

有关线程信号的讨论,请参见此处:

将其设为守护进程线程,它将随程序一起消失。将循环更改为
while(!thread.interrupted())如何将守护进程线程输入到线程池@shmoselMake它是一个守护进程线程,它将随程序一起消亡。将循环更改为
while(!thread.interrupted())如何将守护进程线程输入到线程池@什莫塞尔