多线程场景下利用ThreadLocal是线程安全?

多线程测试代码:

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{
     
        @Override
        public 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{
     
        @Override
        public Thread newThread(Runnable r) {
     
            return new Thread(r, "my thread-" + i++);
        }
    }

}

输出结果:

多线程场景下利用ThreadLocal是线程安全?_第1张图片

你可能感兴趣的:(#,核心技术,Java)