gpt4 book ai didi

java - 为什么我不能取消我的遗嘱执行人提交的工作?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:59:41 24 4
gpt4 key购买 nike

我试图取消使用此代码提交的主题,但没有成功

  ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Object> future = executor.submit(()-> {while(true) { System.out.println("Thread"); Thread.yield();} } );
Thread.sleep(3000);
future.cancel(true);
executor.shutdown();

但线程保持运行。当使用 sleep 而不是 yield 时,线程确实会被取消。例如,这会取消线程:

  ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Object> future = executor.submit(()-> {while(true) { System.out.println("Thread"); Thread.sleep(1000);} } );
Thread.sleep(3000);
future.cancel(true);
executor.shutdown();

这是怎么回事?我是否遗漏了文档中的某些内容?

最佳答案

您的第一个任务对中断没有反应。但是第二个任务是响应式的,因为 Thread.sleep 是一种响应中断的阻塞方法。解决该问题的一种方法是让您的任务响应中断。这是它的样子。

Future<?> future = executor.submit(() -> {
while (!Thread.currentThread().isInterrupted())
System.out.println("Thread");
});

此外,Thread.yield 只是一个调度程序提示,以产生其当前使用的处理器。此操作依赖于平台,不应在实践中使用。因此,我已将其从我的答案中删除。

关于java - 为什么我不能取消我的遗嘱执行人提交的工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58079275/

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