關(guān)于ThreadLocal的使用
1.線程中要使用的類.各線程只有其一個(gè)引用.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");
??????
?????? //延時(shí)20秒后,終止5個(gè)線程
?????? 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.測試結(jié)果:
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.結(jié)果說明:雖然各線程使用的是同一個(gè)對象的引用,但由于使用了ThreadLocal,實(shí)際上每個(gè)線程所操作的數(shù)據(jù)是不一樣的.
posted on 2006-09-25 16:18 2195113 閱讀(226) 評論(0) 編輯 收藏 所屬分類: Base Knowledge