java多线程系列三之ThreadLocal

ThreadLocal当前线程副本

构造方法

    • Constructor and Description
      ThreadLocal()

      Creates a thread local variable.

      创建一个本地线程变量

 该类包含的方法

    • Modifier and TypeMethod and Description
      Tget()

      Returns the value in the current thread's copy of this thread-local variable.

      返回当前线程所对应的线程局部变量

      protected TinitialValue()

      Returns the current thread's "initial value" for this thread-local variable.

      返回该线程局部变量的初始值

      voidremove()

      Removes the current thread's value for this thread-local variable.

      将当前线程局部变量的值删除

      voidset(T value)

      Sets the current thread's copy of this thread-local variable to the specified value.

      设置当前线程的线程局部变量

      static <S> ThreadLocal<S>withInitial(Supplier<? extends S> supplier)

      Creates a thread local variable.

      创建一个线程局部变量

 

 

给个使用例子

public class ThreadMain{
    private static ThreadLocal<Integer> seqNum=new ThreadLocal<Integer>(){

//一般声明在静态变量中,所以后面注意要调用//remove()方法
        public Integer initialValue(){
            return 0;
        }
    };
    public ThreadLocal<Integer> getThreadLocal(){
        return seqNum;
    }

    public int getNextNum(){
        seqNum.set(seqNum.get()+1);
        return seqNum.get();
    }
public static void main(String[] args) {
        ThreadMain sn=new ThreadMain();
        TestClient t1=new TestClient(sn);
        TestClient t2=new TestClient(sn);
        TestClient t3=new TestClient(sn);
        t1.start();
        t2.start();
        t3.start();
    }
    private static class TestClient extends Thread{
        private ThreadMain sn;
        public TestClient(ThreadMain sn){
            this.sn=sn;
        }
        public void run(){
            for (int i=0;i<3;i++) {
                System.out.println("thread["+Thread.currentThread().getName()+"]-->sn["+sn.getNextNum()+"]");
                
            }
            sn.getThreadLocal().remove();//每个线程用完的时候记得删除,避免内存泄露
        }
    }
}

运行结果如下

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值