Java多執行緒(有返回值)的使用
阿新 • • 發佈:2021-07-15
package com.ljq.test.thread; 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; public class CallableFutureTest { @SuppressWarnings("unchecked") public static void main(String[] args) throws ExecutionException, InterruptedException { CallableFutureTest test = new CallableFutureTest(); // 建立一個執行緒池 ExecutorService pool = Executors.newFixedThreadPool(2); // 建立兩個有返回值的任務 Callable c1 = test.newMyCallable("A"); Callable c2 = test.new MyCallable("B"); // 執行任務並獲取Future物件 Future f1 = pool.submit(c1); Future f2 = pool.submit(c2); // 從Future物件上獲取任務的返回值,並輸出到控制檯 System.out.println(">>>" + f1.get().toString()); System.out.println(">>>" + f2.get().toString()); // 關閉執行緒池 pool.shutdown(); } @SuppressWarnings("unchecked") class MyCallable implements Callable { private String name; MyCallable(String name) { this.name = name; } public Object call() throws Exception { return name + "任務返回的內容"; } } }
>>>A任務返回的內容
>>>B任務返回的內容