一個主線程下有多個子線程任務,主線程必須在100秒內將子線程執行的集合結果進行處理返回


一個主線程下有多個子線程任務,主線程必須在100秒內將子線程執行的集合結果進行處理返回

實現代碼:

package cmd.chengxuyuanzhilu.async;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @author 微信公眾號:程序員之路
 *
 */
class Task implements Callable<String> {
    @Override
    public String call() throws Exception {
        System.out.println(String.format("子線程 %s: 在進行計算", Thread.currentThread().getName()));
        Thread.sleep(6000);
        int sum = 0;
        for (int i = 0; i < 100; i++)
            sum += i;
        return "子進程"+Thread.currentThread().getName()+":"+sum;
    }
}

/**
 * @author 微信公眾號:程序員之路
 *
 */
public class Test {
    public static void main(String[] args) {
        //個人建議,控制線程池中線程的個數,防止開啟過多線程造成系統崩潰
        ExecutorService executor = Executors.newFixedThreadPool(5);
        
        //創建100個任務
        List<Task> tasks = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            Task task = new Task();
            tasks.add(task);
        }
        
        //ExecutorService的invokeAll方法執行任務集合中的所有任務,並設置超時時間(100秒)。超時后的任務將取消進行
        List<Future<String>> futures = new ArrayList<>();
        try {
            futures = executor.invokeAll(tasks, 100, TimeUnit.SECONDS);//注:執行所有的方法執行完的時間不能超過100秒,超時后的任務將取消執行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executor.shutdown();
        
        Integer i = 1;
        Integer j = 0;
        for (Future<String> future : futures) {
            try {
                System.out.println(i+" : "+future.get());
                i++;
            }catch (Exception e) {
                j++;
            } 
        }
        System.out.println("未成功執行的任務個數:"+j);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM