---
title: "Threadlocal"
author: "thaIm"
date: "2015-04-08T22:29:47Z"
tags: []
categories: ["编程语言"]
slug: "threadlocal"
draft: false
lastmod: "2015-04-08T22:37:10Z"
id: 2200415
url: "https://thaim.iteye.com/blog/2200415"
---

**一）什么是threadlocal**
    java.lang.ThreadLocal，ThreadLocal为解决多线程程序的并发问题提供了一种新的思路。使用这个工具类可以很简洁地编写出优美的多线程程序，ThreadLocal并不是一个Thread，而是Thread的**局部变量**。
    1）ThreadLocal不是线程，是线程的一个变量
    2）为每个线程维护一个副本（姑且成为‘拷贝’容易理解），让每个线程独立访问
    3）ThreadLocal适用于资源共享但不需要维护状态的情况，也就是一个线程对资源的修改，不影响另一个线程的运行；这种设计是‘空间换时间’，synchronized顺序执行是‘时间换取空间’。

**二）threadlocal的4个函数**
    **1）void set(Object value)**设置当前线程的线程局部变量的值。
    **2）public Object get()**该方法返回当前线程所对应的线程局部变量。
    **3）public void remove()**将当前线程局部变量的值删除，目的是为了减少内存的占用，该方法是JDK 5.0新增的方法。需要指出的是，当线程结束后，对应该线程的局部变量将自动被垃圾回收，所以显式调用该方法清除线程的局部变量并不是必须的操作，但它可以加快内存回收的速度。
    **4）protected Object initialValue()**返回该线程局部变量的初始值，该方法是一个protected的方法，显然是为了让子类覆盖而设计的。这个方法是一个延迟调用方法，在线程第1次调用get()或set(Object)时才执行，并且仅执行1次。ThreadLocal中的缺省实现直接返回一个null。

**三）代码样例**

```java
package com.threadlocal;

public class TestNum {  
    //通过匿名内部类覆盖ThreadLocal的initialValue()方法，指定初始值  
    private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>() {  
        public Integer initialValue() {  
            return 0;  
        }  
    };  
  
    //获取下一个序列值  
    public int getNextNum() {  
        seqNum.set(seqNum.get() + 1);  
        return seqNum.get();  
    }  
  
    private static class TestClient extends Thread {  
        private TestNum sn; //被线程共享的sn 
  
        public TestClient(TestNum sn) {  
            this.sn = sn;  
        }  
  
        public void run() {  
        	//每个线程打出3个序列值
            for (int i = 0; i < 3; i++) {  
                //线程名+sn Number                  
                System.out.println("thread[" + thread.currentthread().getname() + "] --> sn["  + sn.getnextnum() + "]");  
            }  
        }  
    }  
    
    public static void main(String[] args) {  
        TestNum sn = new TestNum();  
        //产生3个线程，3个线程共享sn，各自产生序列号  
        TestClient t1 = new TestClient(sn);  
        TestClient t2 = new TestClient(sn);  
        TestClient t3 = new TestClient(sn);  
        t1.start();  
        t2.start();  
        t3.start();  
    }  
 
} 
```

代码运行的结果大致为：
thread --> sn
thread --> sn
thread --> sn
thread --> sn
thread --> sn
thread --> sn
thread --> sn
thread --> sn
thread --> sn

三个线程都有自己独立的sn数值，互不影响。尽管它们共享了TestNum sn中的Threadlocal seqNum 。