可以被取消的非同步任務(執行緒)
阿新 • • 發佈:2019-01-30
package com.chen.thread.example1; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * 可以被取消的非同步任務, 執行緒 * @author shixiang.chen */ public class MyFutureTaskTest { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(2); /** * 然後告訴submit方法就行了,如果你只需要一個特定的結果,就把那個特定的結果告訴submit方法然後把你想要的特定結果也告訴他, * 它只是幫你完成以前使用Future模式的時候你自己需要做的那些步驟而已,如果你不需要一個結果,那麼就老老實實使用execute */ Future<String> future = executor.submit(new Callable<String>() { /** * call方法可以丟擲異常 */ @Override public String call() throws Exception { try { Thread.sleep(5* 1000); return "Hello Welcome!"; } catch(Exception e) { throw new Exception("Callable terminated with Exception!"); } } }); long t = System.currentTimeMillis(); try { System.out.println("get()前, 這行程式碼不會阻塞, 會執行"); String result = null; try { result = future.get(3000, TimeUnit.MILLISECONDS); // 阻塞式的方法,阻塞執行緒,取得結果,同時設定超時執行時間為5秒。 } catch (TimeoutException e) { e.printStackTrace(); } boolean cancelle = future.isCancelled(); boolean done = future.isDone(); System.err.println("result is " + result + ", time is " + (System.currentTimeMillis() - t)); System.err.println("cancelle:" + cancelle + " , done:" + done); } catch (InterruptedException e) { future.cancel(true); System.err.println("Interrupte time is " + (System.currentTimeMillis() - t)); } catch (ExecutionException e) { future.cancel(true); System.err.println("Throw Exception time is " + (System.currentTimeMillis() - t)); } finally { executor.shutdown(); //關閉 } } }