多線程訪問共享可變數據時,涉及到線程間數據同步問題。
數據都被封閉在各自的線程之中,就不需要同步,這種通過將數據封閉在線程中,而避免使同步的技術,稱爲線程封閉。
ThreadLocal
- 線程級別變量
- 每個線程都有一個ThreadLocal
- 每個線程都擁有了自己獨立的一個變量
- 競爭條件被徹底消除了
- 在併發模式下是絕對安全的變量
1.示例
import java.text.SimpleDateFormat;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class ThreadLocalDemo implements Runnable {
ThreadLocal<SimpleDateFormat> simpleDateFormatThreadLocal =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
public static void main(String[] args) throws InterruptedException {
ThreadLocalDemo threadLocalDemo = new ThreadLocalDemo();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(threadLocalDemo, String.valueOf(i));
TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000));
thread.start();
}
}
@Override
public void run() {
System.out.println("Thread name = " + Thread.currentThread().getName()
+ ", default formatter = " + simpleDateFormatThreadLocal.get().toPattern());
try {
TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
simpleDateFormatThreadLocal.set(new SimpleDateFormat());
System.out.println("Thread name = " + Thread.currentThread().getName()
+ ", formatter = " + simpleDateFormatThreadLocal.get().toPattern());
}
}
輸出
Thread name = 0, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 0, formatter = yy-M-d ah:mm
Thread name = 1, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 2, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 1, formatter = yy-M-d ah:mm
Thread name = 3, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 2, formatter = yy-M-d ah:mm
Thread name = 3, formatter = yy-M-d ah:mm
Thread name = 4, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 5, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 4, formatter = yy-M-d ah:mm
Thread name = 5, formatter = yy-M-d ah:mm
Thread name = 6, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 6, formatter = yy-M-d ah:mm
Thread name = 7, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 8, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 8, formatter = yy-M-d ah:mm
Thread name = 9, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 7, formatter = yy-M-d ah:mm
Thread name = 9, formatter = yy-M-d ah:mm
雖然Thread-0已經改變了formatter的值,顯然其他線程的默認formatter格式沒有受到影響。
2.原理分析
在Thread類中有如下屬性
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
默認情況下,threadLocals屬性值爲null。只有當調用ThreadLocal的set()、get()方法時,如果爲null則調用createMap()賦初值。
/**
* Sets the current thread's copy of this thread-local variable
* to the specified value. Most subclasses will have no need to
* override this method, relying solely on the {@link #initialValue}
* method to set the values of thread-locals.
*
* @param value the value to be stored in the current thread's copy of
* this thread-local.
*/
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
/**
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @return the map
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
/**
* Create the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @param firstValue value for the initial entry of the map
*/
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
最終,變量存儲在ThreadLocalMap中,key爲ThreadLocal對象。