java~並行計算~Future和Callable實現大任務的並行處理


Callable是一個泛型接口,也是一個FunctionalInterface,即函數式接口,它可以使用在Lambda表達式上,即現在比較流行的函數式編程,其實java8之后,封裝了好多函數式接口,今天說的Callable它是一個帶有返回值的接口,它主要和Future一起使用,用在並行計算上;並行計算就是說,一個大任務,多個線程並發執行,這樣可以縮減程序運行的時間,當然前提是你要保持線程的安全性。

大任務實現類

/**
     * 干一件不好干的事,使用Callable接口,需要 FutureTask實現類的支持,用於接收運算結果.
     */
    class DoWork implements Callable<Integer> {

        /**
         * 需要處理的對象集合,每個線程傳遞自己的對象.
         */
        List<String> list;

        public DoWork(List<String> list) {
            this.list = list;
        }

        @Override
        public Integer call() throws Exception {
            for (String s : list) {
                System.out.println(Thread.currentThread().getId() + ":" + s);
            }
            Thread.sleep(3000);
            return 1;
        }
    }

主方法中拆分大對象,調用大任務方法

 @GetMapping("/do-fast")
    public void doFast() throws InterruptedException, ExecutionException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ExecutorService executor = Executors.newFixedThreadPool(2);
        List<Future<Integer>> results = executor.invokeAll(asList(
                new DoWork(Arrays.asList("a","b")), new DoWork(Arrays.asList("c","d"))
        ));
        executor.shutdown();

        //合並結果
        for (Future<Integer> result : results) {
            System.out.println(result.get());
        }
        stopWatch.stop();
        System.out.println(stopWatch.getLastTaskTimeMillis());
    }

如果不使用並行計算,這兩個方法執行應該是3秒+3秒=6秒,而使用了並行編程,它只有3秒左右


免責聲明!

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



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