package LearnCases; import java.io.IOException; import java.util.concurrent.*; public class ThreadLocalTest { //当前 static ThreadLocal<String> localVar = new ThreadLocal<>(); private static ExecutorService workerPool; static void print(String str,boolean isRemove) { //打印当前线程中本地内存中本地变量的值 System.out.println(str + " :" + localVar.get()); //清除本地内存中的本地变量 if(isRemove){ localVar.remove(); } } public static <T> void main(String[] args) throws ExecutionException, InterruptedException { Thread t1 = new Thread(new Runnable() { @Override public void run() { //设置线程1中本地变量的值 localVar.set("localVar1"); //调用打印方法 print("thread1",false); //打印本地变量 System.out.println("after remove : " + localVar.get()); } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { //设置线程1中本地变量的值 localVar.set("localVar2"); //调用打印方法 print("thread2",true); //打印本地变量 System.out.println("after remove : " + localVar.get()); } }); t1.start(); t2.start(); //callable是有返回值的 workerPool = Executors.newCachedThreadPool(); Future<T> acceptFuture; acceptFuture = workerPool.submit(new Callable<T>() { @Override public T call() throws Exception { return (T) "333"; } }); T d= (T) acceptFuture.get(); System.out.println("after remove : " + d); workerPool.shutdown(); } }
作用,每个线程内部的开个内存地址。