1?ThreadLocal接口出現原因
使用ThreadLocal保存當前線程的變量值,這樣你想獲取該變量的值的時候,獲取到的都是本線程的變量值,不會獲取到其他線程設置的值,早在JDK 1.2的版本中就提供java.lang.ThreadLocal,ThreadLocal為解決多線程程序的并發問題提供了一種新的思路。使用這個工具類可以很簡潔地編寫出優美的多線程程序
?
?
?
2 接口主要的API
void set(Object value)設置當前線程的線程局部變量的值。
public Object get()該方法返回當前線程所對應的線程局部變量。
public void remove()將當前線程局部變量的值刪除,目的是為了減少內存的占用,該方法是JDK 5.0新增的方法。需要指出的是,當線程結束后,對應該線程的局部變量將自動被垃圾回收,所以顯式調用該方法清除線程的局部變量并不是必須的操作,但它可以加快內存回收的速度。
protected Object initialValue()返回該線程局部變量的初始值,該方法是一個protected的方法,顯然是為了讓子類覆蓋而設計的。這個方法是一個延遲調用方法,在線程第1次調用get()或set(Object)時才執行,并且僅執行1次。ThreadLocal中的缺省實現直接返回一個null。
?
?
?
3 測試Demo
//'main' method must be in a class 'Rextester'.
//Compiler version 1.8.0_111import java.util.*;
import java.lang.*;class Rextester { //通過匿名內部類覆蓋ThreadLocal的initialValue()方法,指定初始值 private static ThreadLocal<Integer> tLocal = new ThreadLocal<Integer>() { public Integer initialValue() { return 0; } }; //獲取下一個序列值 public int getNextNum() { tLocal.set(tLocal.get() + 1); return tLocal.get(); } public static void main(String args[]) {Rextester rt = new Rextester(); // 3個線程共享rtTestClient t1 = new TestClient(rt); TestClient t2 = new TestClient(rt); TestClient t3 = new TestClient(rt); t1.start(); t2.start(); t3.start(); }private static class TestClient extends Thread { private Rextester rt; public TestClient(Rextester rt) { this.rt = rt; } public void run() { for (int i = 0; i < 3; i++) { // 每個線程打出3個序列值 System.out.println("thread[" + Thread.currentThread().getName() + "] --> rt[" + rt.getNextNum() + "]"); } } }
}
?
?
?
4 運行結果
thread[Thread-0] --> rt[1]
thread[Thread-2] --> rt[1]
thread[Thread-1] --> rt[1]
thread[Thread-0] --> rt[2]
thread[Thread-1] --> rt[2]
thread[Thread-0] --> rt[3]
thread[Thread-2] --> rt[2]
thread[Thread-1] --> rt[3]
thread[Thread-2] --> rt[3]
?