每個(gè)線程提供不同的變量拷貝 PRivate static ThreadLocal<Integer> x = new ThreadLocal<Integer>();

例子:
//每個(gè)線程提供不同的變量拷貝public class TraditionalThreadLoal { static Integer itCommon = new Integer(0);//每個(gè)線程會擁有獨(dú)自it變量public static void main(String[] args) {final ThreadLocal<Integer> it = new ThreadLocal<>();//每個(gè)線程會擁有獨(dú)自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();}}
|
新聞熱點(diǎn)
疑難解答