java學習筆記---多線程的實現2------CompletableFuture

多線程實現方式1:https://blog.csdn.net/qq_39849328/article/details/103303432

多線程之通過completableFuture實現多線程:

import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.junit.Test;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;

public class CompletableFutureStudyFun1 {
    private volatile Integer baseNum = 1;
    AtomicInteger counter = new AtomicInteger(0);

    @Test
    public void executorServiceTestService() {
        List<CompletableFuture<Integer>> futureList = Lists.newArrayList();

        //創建線程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor( 3, 4, 60L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1024), new ThreadFactoryBuilder().setNameFormat("service_test").build(), new ThreadPoolExecutor.AbortPolicy());
        //通過completableFuture,循環調用資源。
        for (int i = 0; i<10; i++) {
            final int per = i==0 ? 1 : i;
            CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> getSumForParam(per), threadPoolExecutor);
            //無需等待結果,主線程繼續執行。
            futureList.add(future);
        }

        //獲得返回結果
        List<Integer> futureCallBack = Lists.newArrayList();

        futureList.stream().forEach(future -> {
            try {
                //獲得線程返回值。
                int res = future.exceptionally(e -> { return null;}).get(60, TimeUnit.SECONDS);
                //添加到線程結果列表
                futureCallBack.add(res);
                System.out.println("=======>>>>>>>>>>>>>>"+res);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        });
        //循環打印
        futureCallBack.stream().forEach(System.out::println);
        //用於debug查看各個參數值,判斷實現情況
        System.out.println("================");
    }

    /**
     * @description 多線程執行方法。
     * @param per
     * @return
     * @eg synchronized保證參數有序性,並且嘗試使用cas
     */
    public /*synchronized*/ int getSumForParam(int per) {
        
        //System.out.print( counter.incrementAndGet() + " ");
        return baseNum++;
    }

}

作者原創:僅用於學習分享和記錄,請求轉載。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章