ThreadLocal

1.ThreadLocal API

  ThreadLocal类只有三个方法:

    > void set(T value):保存值;

    >  T get():获取值;

    > void remove():移除值。

ThreadLocal通常用在一个类的成员(属性)上

多个线程访问它时,每个线程都有自己的副本,互不干扰!

class User{
  private ThreadLocal<String> usernameTl=new ThreadLocal<String>();  
}

代码示例:

public class Demo1 {

    @Test
    public void fun1(){
        final ThreadLocal<String> tl=new ThreadLocal<String>();
        tl.set("hello");////
        System.out.println(tl.get());
        //tl.remove();//移除null
        System.out.println(tl.get());
        
        new Thread(){
            public void run(){
                System.out.println("内部类:"+tl.get());
            }
        
        }.start();
    }
}
//内部实现private Map<Thread,T> map=new HashMap<Thread,T>();
/*
 * 使用当前线程做key
 * set(){
 * map.put(Thread.currentThread(),xx);
 * }
 */

 

posted @ 2019-05-28 15:07  微微亮  阅读(98)  评论(0编辑  收藏  举报