FutureTask多任務併發處理

  • 多任務併發處理加快處理效率,比如投資網站首頁需要加載新聞頭條、理財產品、投資數據等

package com.study.thread;

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

public class FutureTest {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        new  FutureTest().exec();
    }
    void exec() throws InterruptedException, ExecutionException {
        //進行異步任務列表
        List<FutureTask<Integer>> futureTasks = new ArrayList<FutureTask<Integer>>();
        //線程池 初始化十個線程 和JDBC連接池是一個意思 實現重用
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        long start = System.currentTimeMillis();
        //類似與run方法的實現 Callable是一個接口,在call中手寫邏輯代碼
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                Integer res = new Random().nextInt(100);
                Thread.sleep(1000);
                System.out.println("任務執行:獲取到結果 :"+res);
                return  res;
            }
        };

        for(int i=0;i<10;i++){
            //創建一個異步任務
            FutureTask<Integer> futureTask = new FutureTask<Integer>(callable);
            futureTasks.add(futureTask);
            //提交異步任務到線程池,讓線程池管理任務 特爽把。
            //由於是異步並行任務,所以這裏並不會阻塞
            executorService.submit(futureTask);
        }

        int count = 0;
        for (FutureTask<Integer> futureTask : futureTasks) {
            //futureTask.get() 得到我們想要的結果
            //該方法有一個重載get(long timeout, TimeUnit unit) 第一個參數爲最大等待時間,第二個爲時間的單位
            count+= futureTask.get();
        }
        long end = System.currentTimeMillis();
        System.out.println("線程池的任務全部完成:結果爲:"+count+",main線程關閉,進行線程的清理");
        System.out.println("使用時間:"+(end-start)+"ms");
        //清理線程池
        executorService.shutdown();

    }

}

  

輸出:

任務執行:獲取到結果 :32
任務執行:獲取到結果 :75
任務執行:獲取到結果 :92
任務執行:獲取到結果 :49
任務執行:獲取到結果 :6
任務執行:獲取到結果 :75
任務執行:獲取到結果 :33
任務執行:獲取到結果 :27
任務執行:獲取到結果 :20
任務執行:獲取到結果 :14
線程池的任務全部完成:結果爲:423,main線程關閉,進行線程的清理
使用時間:1004ms

 

  • 多線程併發處理集合數據

package com.study.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class FutureTest2 {

    /**
     * 對數據按照分組大小進行分組
     *
     * @param groups      需要分組的數據
     * @param groupNumber 分組大小,默認爲100
     * @return 分組後的數據集合
     */
    public static <T> List<List<T>> groupByNumber(List<T> groups, int groupNumber) {
        List<List<T>> groupList = new ArrayList<>();
        List<T> detailList = new ArrayList<>();
        for (int i = 0; i < groups.size(); i++) {
            detailList.add(groups.get(i));
            if (detailList.size() == groupNumber || (i == (groups.size() - 1))) {
                groupList.add(detailList);
                detailList = new ArrayList<>();
            }
        }
        return groupList;
    }

    public static void main(String[] args) {
        List<String> aa = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            aa.add(String.valueOf(new Random().nextInt(100)));
        }

        //集合分組
        List<List<String>> aaList = groupByNumber(aa, 100);

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        List<Future<String>> futures = new ArrayList<Future<String>>();

        for (int i = 0; i < aaList.size(); i++) {
            final List<String> tlist = aaList.get(i);
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    for (String s : tlist) {
                        System.out.println(Thread.currentThread().getName() + ":" + s);
                    }
                }
            });
        }

    }

}

輸出:

pool-1-thread-2:98
pool-1-thread-1:30
pool-1-thread-1:91
pool-1-thread-1:23
pool-1-thread-1:72
pool-1-thread-1:99
pool-1-thread-3:12
pool-1-thread-3:55
pool-1-thread-3:53
pool-1-thread-3:57
pool-1-thread-3:57
pool-1-thread-2:26
pool-1-thread-2:69
pool-1-thread-2:76
pool-1-thread-2:32
pool-1-thread-2:34
pool-1-thread-2:16
pool-1-thread-2:98
pool-1-thread-2:16
pool-1-thread-2:25
pool-1-thread-2:48
pool-1-thread-2:6
pool-1-thread-2:10
pool-1-thread-2:18

 

發佈了18 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章