gpt4 book ai didi

java - Future.cancel() 方法不起作用

转载 作者:搜寻专家 更新时间:2023-11-01 01:17:40 32 4
gpt4 key购买 nike

我的代码创建了一个 Callable 实例,并使用 ExecutorService 创建了一个新线程。如果线程未完成执行,我想在一定时间后终止该线程。在阅读了 jdk 文档后,我意识到 Future.cancel() 方法可用于停止线程的执行,但令我沮丧的是它不起作用。当然 future.get() 方法在规定的时间(在我的例子中是 2 秒)之后向线程发送一个中断,甚至线程正在接收这个中断但是这个中断只有在线程完成执行后才会发生完全地。但我想在 2 秒后终止线程。

谁能帮我实现这个目标。

测试类代码:

====================================

public class TestExecService {

public static void main(String[] args) {

//checkFixedThreadPool();
checkCallablePool();

}

private static void checkCallablePool()
{
PrintCallableTask task1 = new PrintCallableTask("thread1");

ExecutorService threadExecutor = Executors.newFixedThreadPool(1);
Future<String> future = threadExecutor.submit(task1);

try {
System.out.println("Started..");
System.out.println("Return VAL from thread ===>>>>>" + future.get(2, TimeUnit.SECONDS));
System.out.println("Finished!");
}
catch (InterruptedException e)
{
System.out.println("Thread got Interrupted Exception ==============================>>>>>>>>>>>>>>>>>>>>>>>>>");
//e.printStackTrace();
}
catch (ExecutionException e)
{
System.out.println("Thread got Execution Exception ==============================>>>>>>>>>>>>>>>>>>>>>>>>>");
}
catch (TimeoutException e)
{
System.out.println("Thread got TimedOut Exception ==============================>>>>>>>>>>>>>>>>>>>>>>>>>");
future.cancel(true);
}

threadExecutor.shutdownNow();

}
}

可调用类代码:

===================================================================
package com.test;

import java.util.concurrent.Callable;

public class PrintCallableTask implements Callable<String> {

private int sleepTime;
private String threadName;

public PrintCallableTask(String name)
{
threadName = name;
sleepTime = 100000;
}

@Override
public String call() throws Exception {

try {
System.out.printf("%s going to sleep for %d milliseconds.\n", threadName, sleepTime);
int i = 0;

while (i < 100000)
{
System.out.println(i++);
}


Thread.sleep(sleepTime); // put thread to sleep
System.out.printf("%s is in middle of execution \n", threadName);

} catch (InterruptedException exception) {
exception.printStackTrace();
}


System.out.printf("%s done sleeping\n", threadName);

return "success";
}

}

最佳答案

您的代码一切正常。唯一的问题是您没有在 while 循环中检查 Thread.isInterrupted。线程获取消息的唯一方法是进入阻塞调用 Thread.sleep,它将立即抛出 InterruptedException。如果循环很长,则可能需要一些时间。这正是您的代码有点无响应的原因。

检查中断状态,例如,每 10,000 次迭代:

while (i < 100000) {

if (i % 10000 == 0 && Thread.currentThread().isInterrupted())
return "fail";

System.out.println(i++);
}

InterruptedException 用于冗长的阻塞方法。 Thread.isInterrupted 用于其他一切。

关于java - Future.cancel() 方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13623445/

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