前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >高并发 threadlocal+countDownLatch+线程池走起来

高并发 threadlocal+countDownLatch+线程池走起来

作者头像
gfu
发布2019-11-27 22:56:00
9030
发布2019-11-27 22:56:00
举报
文章被收录于专栏:gfugfu
  • 线程池的创建和使用
  • threadlocal的使用
  • countDownLatch的使用
  • 高并发场景的使用
代码语言:javascript
复制
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联系我
 * @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 {
            // 等待线程全部执行完成
            threadPoolExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 判断线程是否全部执行完成
        boolean terminated = threadPoolExecutor.isTerminated();

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

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


}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档