package com.nanjing.gulimall.zhouyimo.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author zhou
* @version 1.0
* @date 2024/3/17 11:05 下午
*/
class MyData{
ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);
public void add(){
threadLocal.set(threadLocal.get()+1);
}
}
public class ThreadLocalDemo2 {
public static void main(String[] args) {
MyData myData = new MyData();
ExecutorService threadPool = Executors.newFixedThreadPool(3);
try {
for (int i = 0; i < 10; i++) {
threadPool.submit(() -> {
try {
Integer beforeInt = myData.threadLocal.get();
myData.add();
Integer afterInt = myData.threadLocal.get();
System.out.println("当前线程:"+Thread.currentThread().getName()+",beforeInt:"+beforeInt+",afterInt:"+afterInt);
} finally {
myData.threadLocal.remove();
}
});
}
} catch (Exception e) {
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
}
当前线程:pool-1-thread-2,beforeInt:0,afterInt:1
当前线程:pool-1-thread-1,beforeInt:0,afterInt:1
当前线程:pool-1-thread-2,beforeInt:0,afterInt:1
当前线程:pool-1-thread-1,beforeInt:0,afterInt:1
当前线程:pool-1-thread-3,beforeInt:0,afterInt:1
当前线程:pool-1-thread-3,beforeInt:0,afterInt:1
当前线程:pool-1-thread-1,beforeInt:0,afterInt:1
当前线程:pool-1-thread-1,beforeInt:0,afterInt:1
当前线程:pool-1-thread-2,beforeInt:0,afterInt:1
当前线程:pool-1-thread-3,beforeInt:0,afterInt:1
ThreadLocal-阿里规范对ThreadLocal要求
最新推荐文章于 2024-09-03 20:17:53 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)