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

2019-11-27 22:56:00 浏览数 (1)

  • 线程池的创建和使用
  • 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);
    }


}

0 人点赞