在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並不能讓任務真正的結束。編程