每个线程提供不同的变量拷贝 PRivate static ThreadLocal<Integer> x = new ThreadLocal<Integer>();
例子:
//每个线程提供不同的变量拷贝public class TraditionalThreadLoal { static Integer itCommon = new Integer(0);//每个线程会拥有独自it变量public static void main(String[] args) {final ThreadLocal<Integer> it = new ThreadLocal<>();//每个线程会拥有独自it变量 new Thread(new Runnable() {@Overridepublic void run() {for(int i=0;i<10;i++){it.set(i);itCommon = i;System.out.println("1->"+it.get());System.out.println("itCommon->"+itCommon);try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}} }).start(); new Thread(new Runnable() {@Overridepublic void run() {for(int i=0;i<10;i++){it.set(i);itCommon = i;System.out.println("2->"+it.get());System.out.println("itCommon->"+itCommon);try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}}}}).start();}}
新闻热点
疑难解答