線程池實現十個線程共同執行一個任務


----原文地址:https://blog.csdn.net/micro_hz/article/details/73865016

 

線程池:多個線程執行一個任務

應用場景:

當有一個批量任務要執行的時候,一個線程執行耗時比較長,分為十個甚至多個線程來執行縮短執行時間;

package threadPool;

import java.util.List;
import java.util.concurrent.*;

public class ExecuteServiceDemo {

    public static void main(String [] args){
        List list = new CopyOnWriteArrayList<>();

        ExecutorService executorService = Executors.newCachedThreadPool();
        CompletionService<String> completionService = new ExecutorCompletionService(executorService);
        ExecuteServiceDemo executeServiceDemo = new ExecuteServiceDemo();
        // 十個
        long startTime = System.currentTimeMillis();
        int count = 0;
        for (int i = 0;i < 10;i ++) {
            count ++;
            GetContentTask getContentTask = new ExecuteServiceDemo.GetContentTask("micro" + i, 10);
            completionService.submit(getContentTask);
        }
        System.out.println("提交完任務,主線程空閑了, 可以去做一些事情。");
        // 假裝做了8秒種其他事情
        try {
            Thread.sleep(8000);
            System.out.println("主線程做完了,等待結果");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            // 做完事情要結果
            for (int i = 0;i < count;i ++) {
                Future<String> result = completionService.take();
                System.out.println(result.get());
            }
            long endTime = System.currentTimeMillis();
            System.out.println("耗時 : " + (endTime - startTime) / 1000);
        }  catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

    static class GetContentTask implements Callable<String> {

        private String name;

        private Integer sleepTimes;

        public GetContentTask(String name, Integer sleepTimes) {
            this.name = name;
            this.sleepTimes = sleepTimes;
        }
        public String call() throws Exception {
            // 假設這是一個比較耗時的操作
            Thread.sleep(sleepTimes * 1000);
            return "當前線程:"+Thread.currentThread().getName()+"this is content : hello " + this.name;
        }

    }


}

 


免責聲明!

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



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