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

  • 线程池的创建和使用
  • threadlocal的使用
  • countDownLatch的使用
  • 高并发场景的使用
import io.netty.util.concurrent.DefaultThreadFactory;

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

/**
 * go go go
 *
 * @author [email protected] | [email protected] | 有问题可以邮箱或者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 entry = new ThreadLocal<>();
        CountDownLatch cdl = new CountDownLatch(10);
        ThreadLocal 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);
    }


}

你可能感兴趣的:(高并发 threadlocal+countDownLatch+线程池走起来)