定义
使用ThreadLocal定义的变量,为每一个线程都提供一个线程独立的副本。简单一点,一个线程一个单例。
简单实例
import java.util.Random;
public class ThreadLocalTestMain {
public static void main(String[] args) throws Throwable {
Thread t= new Thread(()->{
System.out.println("线程ID"+Thread.currentThread().getId()+ ";ID值:"+ThreadLocalTest.getId());
});
Thread t2= new Thread(()->{
System.out.println("线程ID"+Thread.currentThread().getId()+ ";ID值:"+ThreadLocalTest.getId());
System.out.println("线程ID"+Thread.currentThread().getId()+ ";ID值:"+ThreadLocalTest.getId());
System.out.println("线程ID"+Thread.currentThread().getId()+ ";ID值:"+ThreadLocalTest.getId());
System.out.println("线程ID"+Thread.currentThread().getId()+ ";ID值:"+ThreadLocalTest.getId());
System.out.println("线程ID"+Thread.currentThread().getId()+ ";ID值:"+ThreadLocalTest.getId());
});
Thread t3= new Thread(()->{
System.out.println("线程ID"+Thread.currentThread().getId()+ ";ID值:"+ThreadLocalTest.getId());
});
t.start();
t2.start();
t3.start();
}
public static class ThreadLocalTest {
private static ThreadLocal<Integer> ids = ThreadLocal.withInitial(() -> {
System.out.println("线程ID"+Thread.currentThread().getId()+ ";ids值初始化");
return new Random().nextInt(10000);
});
public static Integer getId() {
return ids.get();
}
}
}
输出结果
线程ID12;ids值初始化
线程ID14;ids值初始化
线程ID13;ids值初始化
线程ID12;ID值:2137
线程ID14;ID值:7831
线程ID13;ID值:1443
线程ID13;ID值:1443
线程ID13;ID值:1443
线程ID13;ID值:1443
线程ID13;ID值:1443
结果分析
1:每个线程都会有且只有一次初始化。
2:一个线程只调用gid,并不会再触初始化。
3:综合上面1,2结论,得出:一个程线一个单例。