概述
ThreadLocal用来解决多线程环境中资源竞争的问题。它不是通过加锁的方式,而是通过每个线程保存一份资源的副本,这样各个线程访问本线程自己的那一份儿,从而避免了对资源竞争的问题。
用法
ThreadLocal的用法非常的简单,只用操作两个方法即可:
- set(Tvalue) 往本线程中保存值
- T get() 从本线程中获取值
下面给出一个实例:
public class ThreadLocalExample {
public static class MyRunnable implements Runnable {
private ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
public void run() {
int i = new Random().nextInt(100);
threadLocal.set(i);
System.out.println(threadLocal + "---" + Thread.currentThread().getName() + " set- " + i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println(threadLocal + "---" + Thread.currentThread().getName() + " get- " + threadLocal.get());
}
}
public static void main(String[] args) {
MyRunnable sharedRunnableInstance = new MyRunnable();
Thread thread1 = new Thread(sharedRunnableInstance);
Thread thread2 = new Thread(sharedRunnableInstance);
thread1.start();
thread2.start();
}
}
程序的输出为:
java.lang.ThreadLocal@53545cc1---Thread-0 set- 18
java.lang.ThreadLocal@53545cc1---Thread-1 set- 41
java.lang.ThreadLocal@53545cc1---Thread-0 get- 18
java.lang.ThreadLocal@53545cc1---Thread-1 get- 41