ThreadLocal实现线程范围内共享

  线程范围内共享,即是对相同一段代码,在不同的模块调用时使用一份数据,而在另外一个线程中又使用另外一份数据。

  ThreadLocal使用set方法为一个新的线程增加一条记录,key是各自的线程,value为set进去的值,也就是共享的值。ThreadLocal.clear()清空记录。

  JAVA代码

public class TraditionalThreadSocpeShare {
    private static Map<Thread, Integer> threadLocal = new HashMap<Thread, Integer>();
    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {
            new Thread(new Runnable() {
                public void run() {
                    int data = new Random().nextInt();
                    threadLocal.put(Thread.currentThread(), data);
                    System.out.println(Thread.currentThread().getName()
                            + " data value " + data);
                    new A().get();
                    new B().get();
                }

            }).start();
        }
    }

    static class A {
        public void get() {
            int data = threadLocal.get(Thread.currentThread());
            System.out.println("A from " + Thread.currentThread().getName()
                    + " data value " + data);
        }
    }

    static class B {
        public void get() {
            int data = threadLocal.get(Thread.currentThread());
            System.out.println("B from " + Thread.currentThread().getName()
                    + " data value " + data);
        }
    }
}

 

posted @ 2015-12-31 15:34  哎呦喂,我的小祖宗╰つ  阅读(321)  评论(1编辑  收藏  举报