Java ThreadLocal application
definition
Use ThreadLocal defined variables for each thread will provide a copy of a separate thread. Simply, a thread a singleton.
Simple examples
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();
}
}
}
Output
Thread ID12; ids initializes the value of
the thread ID14; ids initializes the value of
the thread ID13; ids initializes the value of
the thread ID12; ID Found: 2137
thread ID14; ID Found: 7831
thread ID13; ID Found: 1443
thread ID13; ID Found: 1443
thread ID13; ID Found: 1443
thread ID13; ID Found: 1443
thread ID13; ID Found: 1443
Result analysis
1: Each thread has one and only one initialization.
2: a thread calls only gid, and will not touch initialization.
3: 1,2 Comprehensive above conclusion drawn: a one-way line embodiment.