我创建的代码创建了一个 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";
}
}