9.本地线程(ThreadLoca)
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();
}
}