
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