ThreadLocal的测试

package com.ddc.mem;

public class ThreadLocalTestMain {
    ThreadLocal<AddInteger> localArgs=new ThreadLocal<AddInteger>();
    AddInteger intance=new AddInteger();
    public void mainTest(){
        for(int i=0 ;i<10;i++){
            ThreadTest thread=new ThreadTest(i);
            thread.start();
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    class ThreadTest extends Thread {
        public ThreadTest(int name) {
            this.setName("DdcThread-"+name);
        }

        @Override
        public void run() {
            localArgs.set(intance);
            intance.inc(100);
            for(int i=0;i<30;i++){
                AddInteger intThis=localArgs.get();
                intThis.inc(1);
                System.out.println(this.getName()+":"+intThis);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
}
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        ThreadLocalTestMain main=new ThreadLocalTestMain();
        main.mainTest();
    }
    

}

class  AddInteger {
    private int i=0;
    public void inc(int inc){
        i=i+inc;
    }
    public int getI(){
        return i;
    }
}

 

我的理解就是:ThreadLocal其实就相当于一个IdentityHashMap,其key就是当前的线程,value就是当前线程调用set方法设置进去的那个值 。

posted @ 2012-05-15 11:25  xiao晓  阅读(207)  评论(0编辑  收藏  举报