Java實現多執行緒之Callable介面
阿新 • • 發佈:2018-12-23
Java實現多執行緒之Callable介面
/* * 一、建立執行執行緒的方式三:實現 Callable 介面。 相較於實現 Runnable 介面的方式,方法可以有返回值,並且可以丟擲異常。 * * 二、執行 Callable 方式,需要 FutureTask 實現類的支援,用於接收運算結果。 FutureTask 是 Future 介面的實現類 */ public class TestCallable { public static void main(String[] args) { ThreadDemo td = new ThreadDemo(); //1.執行 Callable 方式,需要 FutureTask 實現類的支援,用於接收運算結果。 FutureTask<Integer> result = new FutureTask<>(td); new Thread(result).start(); //2.接收執行緒運算後的結果 try { Integer sum = result.get(); //FutureTask 可用於 閉鎖 System.out.println(sum); System.out.println("------------------------------------"); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } class ThreadDemo implements Callable<Integer>{ @Override public Integer call() throws Exception { int sum = 0; for (int i = 0; i <= 100000; i++) { sum += i; } return sum; } }