高并發(fā) threadlocal+countDownLatch+線程池走起來

  • 線程池的創(chuàng)建和使用
  • threadlocal的使用
  • countDownLatch的使用
  • 高并發(fā)場景的使用
import io.netty.util.concurrent.DefaultThreadFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
 * go go go
 *
 * @author 719383495@qq.com | 719383495qq@gmail.com | 有問題可以郵箱或者github聯(lián)系我
 * @date 2019/11/23 9:07
 */
public class ThreadLocalMain {


    private static final int FOR_TIMES = 10;

    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws InterruptedException {

        ThreadLocal<Map> entry = new ThreadLocal<>();
        CountDownLatch cdl = new CountDownLatch(10);
        ThreadLocal<Integer> threadLocal = new ThreadLocal<>();


        ThreadFactory threadFactory = new DefaultThreadFactory("pool");
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 61, 1, TimeUnit.MINUTES, new LinkedBlockingDeque<>(10000), threadFactory);
        for (int i = 0; i < FOR_TIMES; i++) {
            threadPoolExecutor.execute(() -> {
                try {
                    threadLocal.set(3);
                    cdl.await();
                    Integer j = threadLocal.get();
                    j++;
                    printRet(j);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                Map hashMap = new HashMap<>(16);
                hashMap.put("key", Thread.currentThread().getId());
                System.out.println(Thread.currentThread() + ":set:" + Thread.currentThread().getId());
                entry.set(hashMap);
            });
            cdl.countDown();
        }
        System.out.println("-------------------");
        for (int i = 0; i < FOR_TIMES; i++) {
            threadPoolExecutor.execute(() -> {
                Map map = entry.get();
                System.out.println(Thread.currentThread() + ":get:" + map.get("key"));
            });
        }

        threadPoolExecutor.shutdown();

        try {
            // 等待線程全部執(zhí)行完成
            threadPoolExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 判斷線程是否全部執(zhí)行完成
        boolean terminated = threadPoolExecutor.isTerminated();

        if (terminated) {
            System.out.println("over");
        }
    }

    private static void printRet(Integer integer) {
        System.out.println(integer);
    }


}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容