ThreadLoca
提升一個線程的局部變量,訪問某個線程都有本身的局部變量,當使用ThreadLoca爲每一個使用該變量的線程提供獨立的變量副本,因此每個線程均可以獨立的改變本身的副本,二不會影響到其它線程對應的副本
package com.jlong;
class Res{
ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>(){
@Override
protected Integer initialValue() {
return 0;
}
};
}
class ThreadLoca extends Thread{
private Res res;
public ThreadLoca(Res res){
this.res=res;
}
@Override
public void run() {
for (int i = 0; i <3 ; i++) {
System.out.println(getName()+"----"+i);
}
}
}
public class ThreadLocaTest {
public static void main(String[] args) {
Res res = new Res();
ThreadLoca threadLoca1 = new ThreadLoca(res);
ThreadLoca threadLoca2 = new ThreadLoca(res);
threadLoca1.start();
threadLoca2.start();
}
}