在java并发编程学习之三种线程启动方式中有提过。主要的方法以下: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并不能让任务真正的结束。编程