非同步方法呼叫【其他模式】
阿新 • • 發佈:2019-01-02
public class AsyncMethodInvocation { /** * Async Method Invocation【非同步方法呼叫】 */ @Test public void all() throws InterruptedException, ExecutionException { final String result = "async method invocation"; // 1)可執行的非同步任務呢 final Callable<String> callable = ()->{ // 2)非同步任務的結果 return result; }; // 3)執行非同步任務的執行緒池 final ExecutorService executorService = Executors.newFixedThreadPool(1); final Future<String> future = executorService.submit(callable); // 4)可在將來讀取非同步任務的計算結果 assertEquals(result, future.get()); executorService.awaitTermination(2, TimeUnit.SECONDS); } }