深入实践ThreadLocal

本文通过具体实例探讨了ThreadLocal及InheritableThreadLocal在不同线程模型中的表现,特别是parallelStream线程模型与自定义线程模型下ThreadLocal的继承特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文主要实践,不在同一个线程中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<String> 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<Integer> 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<Integer> 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();


    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值