码迷,mamicode.com
首页 > 编程语言 > 详细

多线程映射工具——线程当地值

时间:2016-12-28 17:27:32      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:for   示例   current   div   private   i++   bsp   工具   自己   

ThreadLocal相当于一个Map<Thread, T>,各线程使用自己的线程对象Thread.currentThread()作为键存取数据,但ThreadLocal实际上是一个包装了这个Map,并且线程只能存取自己的数据,不能操作其它线程的数据。

  • T get()
  • set(T)
  • remove()

代码示例:

public static void main(String[] args) {
    String[] names = new String[]{"A", "B", "C", "D", "E"};
    for(int i=0; i<names.length; i++){
        final String myName = names[i];
        new Thread(){
            public void run(){
                name.set(myName);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                test();
            }
        }.start();
    }
    
    /*
        运行结果:
        Thread-0 -> 我的名字叫A
        Thread-2 -> 我的名字叫C
        Thread-1 -> 我的名字叫B
        Thread-3 -> 我的名字叫D
        Thread-4 -> 我的名字叫E
     */
}

private static ThreadLocal<String> name = new ThreadLocal<String>();

public static void test(){
    System.out.println(Thread.currentThread().getName() + " -> 我的名字叫" + name.get());
}

 

多线程映射工具——线程当地值

标签:for   示例   current   div   private   i++   bsp   工具   自己   

原文地址:http://www.cnblogs.com/hvicen/p/6229832.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!