public class ThreadLocalDemo {
static Integer share; // 共享变量
public static void main(String[] args) throws InterruptedException {
// 创建一个ThreadLocal,初始化值为0
ThreadLocal<Integer> threadLocal = new InheritableThreadLocal();
threadLocal.set(0);
// 创建线程1
Thread thread1 = new Thread(() -> {
share = threadLocal.get() + 1;
});
// 创建线程2
Thread thread2 = new Thread(() -> {
threadLocal.set(share);
share = threadLocal.get() + 1;
});
share = threadLocal.get();
System.out.println("Main thread: share1 = " + share);
// 启动线程1
thread1.start();
thread1.join();
System.out.println("Main thread: share2 = " + share);
// 启动线程2
thread2.start();
thread2.join();
System.out.println("Main thread: share3 = " + share);
}
}
运行结果