在 java并发编程学习之三种线程启动方式 中有提过。主要的方法如下:
public class FutureTaskDemo { static class Thread1 implements Callable { @Override public Object call() throws Exception { System.out.println("before fun"); fun(); System.out.println("after fun"); return null; } public void fun() { while (true) { } } } public static void main(String[] args) { Thread1 thread1 = new Thread1(); FutureTask futureTask = new FutureTask(thread1); Thread thread = new Thread(futureTask); thread.start(); try { Thread.sleep(1000); System.out.println("cancel:" + futureTask.cancel(true)); Thread.sleep(1000); System.out.println("isCancelled:" + futureTask.isCancelled()); System.out.println("isDone:" + futureTask.isDone()); System.out.println(futureTask.get()); } catch (InterruptedException e) { System.out.println("InterruptedException"); } catch (ExecutionException e) { System.out.println("ExecutionException"); } catch (CancellationException e) { System.out.println("CancellationException"); } } }
运行结果如下:
由于任务被取消,所以抛出CancellationException异常。注意的是,此时thread1线程还在跑,isCancelled和isDone返回的是true。cancel并不能让任务真正的结束。