Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 並行編程:用 Callable 與 Future 取得任務回饋

並行任務一旦丟出去,往往就像把信投進信箱——不知道有沒有送達。本文示範如何在 Java 中「強制」取得背景任務的回饋:不只關心工作有沒有跑完,還要知道即時進度與最終成功數量。

場景很具體:一支批次寄信程式,用多執行緒送出大量郵件。你想知道寄成功幾封、也想在執行途中看到百分比進度。

為什麼是 Callable 而不是 Runnable

Callable 的用法與 Runnable 幾乎相同,關鍵差異是它的 call() 方法會回傳一個值,正好用來承載「這次計算的結果」。由於泛型化的關係,回傳型別可以是任何你需要的資訊。

package com.ricardozuasti;

import java.util.concurrent.Callable;

public class FictionalEmailSender implements Callable<Boolean>{
    private String to;
    private String subject;
    private String body;

    public FictionalEmailSender(String to, String subject, String body){
        this.to = to;
        this.subject = subject;
        this.body = body;
    }

    @Override
    public Boolean call() throws InterruptedException {
        // 在 0~0.5 秒間模擬寄信
        Thread.sleep(Math.round(Math.random() * 0.5 * 1000));
        // 假設有 80% 的機率成功
        if(Math.random() > 0.2){
            return true;
        }else{
            return false;
        }
    }
}

用 ThreadPoolExecutor 收集 Future

提交任務時,每個 Callable 都會換回一個 Future 引用,稍後可從它取出結果。這裡刻意直接 new ThreadPoolExecutor,而非使用 Executors 的靜態工具方法,原因是前者提供了 getCompletedTaskCount()、getTaskCount() 等對掌握進度很有幫助的方法。

package com.ricardozuasti;

import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.List;

public class Concurrency2 {
    public static void main(String[] args){
        try{
            ThreadPoolExecutor executor = new ThreadPoolExecutor(30, 30, 1,
                TimeUnit.SECONDS, new LinkedBlockingQueue());
            List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>(9000);

            // 送出大量郵件,帳號假設為 4 位數字
            for(int i = 1000; i < 10000; i++){
                futures.add(executor.submit(new FictionalEmailSender(i + "@sina.com",
                    "Knock, knock, Neo", "The Matrix has you...")));
            }

            // 任務都提交完畢後關閉 executor
            System.out.println("Starting shutdown...");
            executor.shutdown();

            // 每秒印出執行進度
            while(!executor.isTerminated()){
                executor.awaitTermination(1, TimeUnit.SECONDS);
                int progress = Math.round((executor.getCompletedTaskCount() * 100)
                    / executor.getTaskCount());
                System.out.println(progress + "% done ("
                    + executor.getCompletedTaskCount() + " emails have been sent).");
            }

            // 全部送完,檢查 futures 統計成功與失敗
            int errorCount = 0;
            int successCount = 0;
            for(Future<Boolean> future : futures){
                if(future.get()){
                    successCount++;
                }else{
                    errorCount++;
                }
            }
            System.out.println(successCount + " emails were successfully sent, but "
                + errorCount + " failed.");
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}

重點整理

  • Callable<T> 的 call() 回傳 T,適合需要結果的任務。
  • 每個提交都換回一個 Future,用 get() 取值(會阻塞到完成)。
  • shutdown() 之後仍可呼叫 awaitTermination() 做「等待+輪詢進度」。
  • 直接建立 ThreadPoolExecutor 才能取得完成數與總數等統計資訊。
Copyright © Linux教程網 All Rights Reserved