为什么用它?
ThreadLocal概念:线程局部变量,一种多线程间并发访问变量的解决方案。与其synchronized等加锁的方式不同,ThreadLocal不提供锁,使用以空间换时间的手段,为每个线程提供变量的独立副本,以保障线程安全。
从性能上说,ThreadLocal不具有绝对的优势,在并发不是很高的时候,加锁的性能会更好,但作为一套与锁完全无关的线程安全解决方案,在高并发量或者竞争激烈的场景,使用ThreadLocal可以在一定程度上减少锁竞争。
package practice;
public class Task
{
public static ThreadLocal<String> threadLocal = new ThreadLocal<String>();
//包装threadLocal的set/get方法
public void setThreadLocal(String value){
threadLocal.set(value);
}
public String getThreadLocal(){
return threadLocal.get();
}
//测试任务
public static void main(String[] args)
{
Task task = new Task();
Thread t1 = new Thread(new Runnable(){
public void run(){
task.setThreadLocal("战三");
System.out.println("谁在set:"+Thread.currentThread().getName());
System.out.println("谁在get:"+Thread.currentThread().getName()+" 线程里的值:"+threadLocal.get());
}
},"t1");//'t1':参数只是给这个线程命名
Thread t2 = new Thread(new Runnable(){
public void run(){
System.out.println("谁在get:"+Thread.currentThread().getName()+" 线程里的值:"+threadLocal.get());
}
},"t2");
t1.start();
t2.start();
}
}
谁在set:t1
谁在get:t1 线程里的值:战三
谁在get:t2 线程里的值:null
总结:只有t1设置过值,所以t2直接get是得不到值得