文章目录
- 背景
- 多线程场景测试代码
- 结论
背景
ThreadLocal原理以及基本概念这里我就不介绍了,这里我们主要关注ThreadLocal是否是线程安全吗?其实如果我们知道ThreadLocal原理我们肯定知道它是线程安全的,但是我在开发的时候不放心做了个测试,也顺便把测试demo贴一下
多线程场景测试代码
多线程测试代码:
package net.dreamzuora.utils;import java.util.UUID;
import java.util.concurrent.*;public class ThreadLocalMultiThread {ThreadLocal<String> threadLocal = new ThreadLocal<>();public static void main(String[] args) throws InterruptedException {CountDownLatch countDownLatch = new CountDownLatch(1);ThreadPoolExecutor.CallerRunsPolicy callerRunsPolicy = new ThreadPoolExecutor.CallerRunsPolicy();ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<>(200), new MyThreadFactory(), callerRunsPolicy);ThreadLocalMultiThread threadLocalMultiThread = new ThreadLocalMultiThread();for (int k =0; k < 500; k++){threadPoolExecutor.execute(threadLocalMultiThread.new TestWorker());}countDownLatch.await();}class TestWorker implements Runnable{@Overridepublic void run() {try {String s = UUID.randomUUID().toString();System.out.println(System.currentTimeMillis() + " " + Thread.currentThread().getName() + " producer : " + s);threadLocal.set(s);TimeUnit.SECONDS.sleep(1);System.out.println(System.currentTimeMillis() + " " + Thread.currentThread().getName() + "consumer : " + threadLocal.get());threadLocal.remove();} catch (InterruptedException e) {e.printStackTrace();}}}static int i = 0;static class MyThreadFactory implements ThreadFactory{@Overridepublic Thread newThread(Runnable r) {return new Thread(r, "my thread-" + i++);}}}
输出结果:
结论
最终可以发现在用一个线程中生产和消费他们的UUID始终是一致的,因而可以通过测试案例证明他们是线程安全的,可以放心使用啦