1.线程中要使用的类.各线程只有其一个引用.
public class VarClass {
private static ThreadLocal threadVar=new ThreadLocal(){
protected synchronized Object initialValue(){
System.out.println(Thread.currentThread().getName()+" initial value is 1");
return new Integer(1);
}};
public int getValue(){
return ((Integer)threadVar.get()).intValue();
}
public void setValue(){
int a=getValue();
a++;
threadVar.set(new Integer(a));
}
}
2.线程类
public class Worker extends Thread {
private long interval=0;
private boolean isRun=true;
private VarClass v=null;
public Worker(String name,VarClass v,long interval){
setName(name);
this.v=v;
this.interval=interval;
}
public void run() {
while(isRun){
try{
Thread.sleep(interval);
}catch(InterruptedException e){
e.printStackTrace();
}
v.setValue();
}
System.out.println(getName()+" is over at "+v.getValue());
}
public void stopThread(){
isRun=false;
}
}
3.测试类
public class TestThreadLocal {
public static void main(String[] args){
VarClass v=new VarClass();
Worker w1=new Worker("Thread_A",v,100);
Worker w2=new Worker("Thread_B",v,200);
Worker w3=new Worker("Thread_C",v,300);
Worker w4=new Worker("Thread_D",v,400);
Worker w5=new Worker("Thread_E",v,500);
w1.start();
w2.start();
w3.start();
w4.start();
w5.start();
System.out.println("All threads is over after 20 seconds");
//延时20秒后,终止5个线程
try{
Thread.sleep(20000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("All threads will be overed");
w1.stopThread();
w2.stopThread();
w3.stopThread();
w4.stopThread();
w5.stopThread();
}
}
4.测试结果:
All threads is over after 20 seconds
Thread_A initial value is 1
Thread_B initial value is 1
Thread_C initial value is 1
Thread_D initial value is 1
Thread_E initial value is 1
All threads will be overed
Thread_A is over at 200
Thread_B is over at 101
Thread_D is over at 51
Thread_C is over at 68
Thread_E is over at 42
5.结果说明:虽然各线程使用的是同一个对象的引用,但由于使用了ThreadLocal,实际上每个线程所操作的数据是不一样的.