ThreadLocal是每个线程的“独有”空间,可以存放线程的独有变量。
如下例,分别使用ThreadLocal和ArrayList存储两个线程的变量:
import java.util.ArrayList;
import java.util.List;
public class ThreadLocalDemo
{
static ThreadLocal<List<String>> threadLocal = new ThreadLocal<>();
static ArrayList<List<String>> list = new ArrayList<>();
public static void main(String[] args)
throws InterruptedException
{
new Thread(new Runnable(){
@Override
public void run()
{
List<String> value1 = new ArrayList<>();
value1.add("test1");
value1.add("name1");
threadLocal.set(value1);
System.out.println("threadLocal: " + threadLocal.get());
list.add(value1);
System.out.println("arrayList: " + list);
}
}).start();