深入实践ThreadLocal

本文主要实践,不在同一个线程中ThreadLocal的表现。

Thread中持有ThreadLocalMap,分别为threadLocals、inheritableThreadLocals

threadLocals:用于普通的ThreadLocal

inheritableThreadLocals:用于InheritableThreadLocal

问题注意点:

1、如果在子线程读取父线程中设置的ThreadLocal值,InheritableThreadLocal。

2、用线程池处理,不能使用ThreadLocal及InheritableThreadLocal,不然线程池中的取到ThreadLocal的值会错乱。

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author keyhunter
 *         Created on 2018/8/13.
 */
public class TestThreadLocal {

    private static ThreadLocal threadLocal = new InheritableThreadLocal<>();

    private static ExecutorService executorService = Executors.newFixedThreadPool(2);

    public static void setThreadLocal(String msg) {
        threadLocal.set(msg);
    }

    public static void main(String[] args) throws InterruptedException {
        test1();
//        test2();
    }

    /**
     * 测试parallelStream线程模型中,threadLocal的继承
     * 线程池中的ThreadLocal并不会针对任务完成去清理ThreadLoacal
     *
     * @throws InterruptedException
     */
    private static void test1() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(9);
        Thread thread = new Thread(() -> {
            setThreadLocal("十元");
            List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
            list.stream().forEach(x -> System.out.println("stream:" + x + ":" + threadLocal.get()));

            list.forEach(x -> {
                executorService.execute(() -> {
                    threadLocal.set("十元" + x);
                    try {
                        Thread.sleep(new Random().nextInt(500));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("parallelStream:" + x + ":" + threadLocal.get());
                    countDownLatch.countDown();
                });

            });
            list.parallelStream().forEach(x -> {
                threadLocal.set("十元" + x);
                try {
                    Thread.sleep(new Random().nextInt(500));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("parallelStream:" + x + ":" + threadLocal.get());
                countDownLatch.countDown();
            });
        });
        thread.start();
        countDownLatch.await();
        List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        CountDownLatch countDownLatch2 = new CountDownLatch(9);
        list.parallelStream().forEach(x -> {
            System.out.println("last:" + threadLocal.get());
            countDownLatch2.countDown();
        });
        countDownLatch2.await();
        System.out.println(threadLocal.get());
    }

    /**
     * 测试自定义线程模型中,threadLocal的继承
     * 多线程放入ThreadLocal,线程池中线程可能取到错乱的ThreadLocal值
     *
     * @throws InterruptedException
     */
    private static void test2() throws InterruptedException {
        //多个线程里放threadLocal,可能导致子线程池读错
        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            final int finalI = i;
            Thread thread = new Thread(() -> {
                threadLocal.set("十元线程" + finalI);
                try {
                    Thread.sleep(new Random().nextInt(500));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                executorService.execute(() -> {
                    System.out.println("十元线程" + finalI + "value:" + threadLocal.get());
                    countDownLatch.countDown();
                });
            });
            thread.start();
        }
        countDownLatch.await();


    }
}

你可能感兴趣的:(JAVA)