ThreadLocal线程隔离

时间:2024-08-25 19:36:38
 package com.cookie.test;
import java.util.concurrent.atomic.AtomicInteger;
/**
* author : cxq
* Date : 2019/6/20
* 测试ThreadLocal线程隔离
*/
public class ThreadLocalTest {
private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
private static AtomicInteger a = new AtomicInteger(100);
private static int b = 100 ;
public static void main(String[] args) {
new Thread(() -> {
try {
for (int i = 0; i < 100; i++) {
threadLocal.set(i);
// a.decrementAndGet();
b -- ;
System.out.println(Thread.currentThread().getName() + "====" + threadLocal.get());
// System.out.println(Thread.currentThread().getName() + "====" + a.get());
// System.out.println(Thread.currentThread().getName() + "====" + b);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
threadLocal.remove();
}
}, "threadLocal1").start();
new Thread(() -> {
try {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + "====" + threadLocal.get());
// System.out.println(Thread.currentThread().getName() + "====" + a.get());
System.out.println(Thread.currentThread().getName() + "====" + b);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
threadLocal.remove();
}
}, "threadLocal2").start();
}
}

输出结果展示:

ThreadLocal线程隔离

如果采用AtomicInteger a 或者常量 int b :

ThreadLocal线程隔离