Java線程:深刻ThreadLocal
ThreadLocal與線程成員變量還有區別,ThreadLocal該類提供了線程局部變量。這個局部變量與通常的成員變量不同,ThreadLocal的變量在被多個線程使用時候,每一個線程只能拿到該變量的一個副本,這是Java API中的描述,經過閱讀API源碼,發現並不是副本,副本什麼概念?克隆品? 或者是別的樣子,太模糊。
準確的說,應該是ThreadLocal類型的變量內部的註冊表(Map<Thread,T>)發生了變化,但ThreadLocal類型的變量自己的確是一個,這纔是本質!
下面就作個例子:
1、標準例子
定義了MyThreadLocal類,建立它的一個對象tlt,分別給四個線程使用,結果四個線程tlt變量並無出現共用現象,二是各用各的,這說明,四個線程使用的是tlt的副本(克隆品)。
/**
* 使用了ThreadLocal的類
*
* @author leizhimin 2010-1-5 10:35:27
*/
public
class MyThreadLocal {
//定義了一個ThreadLocal變量,用來保存int或Integer數據
private ThreadLocal<Integer> tl =
new ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return 0;
}
};
public Integer getNextNum() {
//將tl的值獲取後加1,並更新設置t1的值
tl.set(tl.get() + 1);
return tl.get();
}
}
/**
* 測試線程
*
* @author leizhimin 2010-1-5 10:39:18
*/
public
class TestThread
extends Thread {
private MyThreadLocal tlt =
new MyThreadLocal();
public TestThread(MyThreadLocal tlt) {
this.tlt = tlt;
}
@Override
public
void run() {
for (
int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName() +
"\t" + tlt.getNextNum());
}
}
}
/**
* ThreadLocal測試
*
* @author leizhimin 2010-1-5 10:43:48
*/
public
class Test {
public
static
void main(String[] args) {
MyThreadLocal tlt =
new MyThreadLocal();
Thread t1 =
new TestThread(tlt);
Thread t2 =
new TestThread(tlt);
Thread t3 =
new TestThread(tlt);
Thread t4 =
new TestThread(tlt);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
能夠看出,三個線程各自獨立編號,互不影響:
Thread-0 1
Thread-1 1
Thread-0 2
Thread-1 2
Thread-0 3
Thread-1 3
Thread-2 1
Thread-3 1
Thread-2 2
Thread-3 2
Thread-2 3
Thread-3 3
Process finished with exit code 0
tlt對象是一個,廢話tl對象也是一個,由於組合關係是一對一的。可是tl對象內部的Map隨着線程的增多,會建立不少Integer對象。只是Integer和int已經通用了。因此感受不到Integer的對象屬性。
2、不用ThreadLocal
假如不用ThreadLocal,只須要將MyThreadLocal類從新定義爲:
/**
* 使用了ThreadLocal的類
*
* @author leizhimin 2010-1-5 10:35:27
*/
public
class MyThreadLocal {
private Integer t1 = 0;
public Integer getNextNum(){
return t1=t1+1;
}
// //定義了一個ThreadLocal變量,用來保存int或Integer數據
// private ThreadLocal<Integer> tl = new ThreadLocal<Integer>() {
// @Override
// protected Integer initialValue() {
// return 0;
// }
// };
//
// public Integer getNextNum() {
// //將tl的值獲取後加1,並更新設置t1的值
// tl.set(tl.get() + 1);
// return tl.get();
// }
}
而後運行測試:
Thread-2 1
Thread-2 2
Thread-1 4
Thread-1 6
Thread-3 3
Thread-3 9
Thread-3 10
Thread-1 8
Thread-0 7
Thread-0 11
Thread-0 12
Thread-2 5
Process finished with exit code 0
從這裏能夠看出,四個線程共享了tlt變量,結果每一個線程都直接修改tlt的屬性。
3、本身實現個ThreadLocal
package com.lavasoft.test2;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* 使用了ThreadLocal的類
*
* @author leizhimin 2010-1-5 10:35:27
*/
public
class MyThreadLocal {
//定義了一個ThreadLocal變量,用來保存int或Integer數據
private com.lavasoft.test2.ThreadLocal<Integer> tl =
new com.lavasoft.test2.ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return 0;
}
};
public Integer getNextNum() {
//將tl的值獲取後加1,並更新設置t1的值
tl.set(tl.get() + 1);
return tl.get();
}
}
class ThreadLocal<T> {
private Map<Thread, T> map = Collections.synchronizedMap(
new HashMap<Thread, T>());
public ThreadLocal() {
}
protected T initialValue() {
return
null;
}
public T get() {
Thread t = Thread.currentThread();
T obj = map.get(t);
if (obj ==
null && !map.containsKey(t)) {
obj = initialValue();
map.put(t, obj);
}
return obj;
}
public
void set(T value) {
map.put(Thread.currentThread(), value);
}
public
void remove() {
map.remove(Thread.currentThread());
}
}
運行測試:
Thread-0 1
Thread-0 2
Thread-0 3
Thread-2 1
Thread-2 2
Thread-3 1
Thread-2 3
Thread-3 2
Thread-1 1
Thread-3 3
Thread-1 2
Thread-1 3
Process finished with exit code 0
很意外,這個山寨版的ThreadLocal也一樣運行很好,實現了JavaAPI中ThreadLocal的功能。
4、透過現象看本質
其實從程序角度看,tlt變量的確是一個,毫無疑問的。可是爲何打印出來的數字就互不影響呢?
是由於使用了Integer嗎?-----不是。
緣由是:protected T initialValue()和get(),由於每一個線程在調用get()時候,發現Map中不存在就建立。調用它的時候,就建立了一個新變量,類型爲T。每次都新建,固然各用個的互不影響了。
爲了看清本質,將Integer換掉,重寫部分類:
package com.lavasoft.test2;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* 使用了ThreadLocal的類
*
* @author leizhimin 2010-1-5 10:35:27
*/
public
class MyThreadLocal {
//定義了一個ThreadLocal變量,用來保存int或Integer數據
// private ThreadLocal<Bean> tl = new ThreadLocal<Bean>() {
private com.lavasoft.test2.ThreadLocal<Bean> tl =
new com.lavasoft.test2.ThreadLocal<Bean>() {
@Override
protected Bean initialValue() {
return
new Bean();
}
};
@Override
public String toString() {
return
"MyThreadLocal{" +
"tl=" + tl +
'}';
}
public Bean getBean() {
return tl.get();
}
}
class ThreadLocal<T> {
private Map<Thread, T> map = Collections.synchronizedMap(
new HashMap<Thread, T>());
public ThreadLocal() {
}
protected T initialValue() {
return
null;
}
public T get() {
Thread t = Thread.currentThread();
T obj = map.get(t);
if (obj ==
null && !map.containsKey(t)) {
obj = initialValue();
map.put(t, obj);
}
return obj;
}
public
void set(T value) {
map.put(Thread.currentThread(), value);
}
public
void remove() {
map.remove(Thread.currentThread());
}
}
package com.lavasoft.test2;
/**
* 測試Bean
*
* @author leizhimin 2010-1-5 14:18:26
*/
public
class Bean {
private String id =
"0";
private String name =
"none";
public Bean() {
}
public Bean(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public
void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public
void setName(String name) {
this.name = name;
}
public String showinfo() {
return
"Bean{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
package com.lavasoft.test2;
/**
* 測試線程
*
* @author leizhimin 2010-1-5 10:39:18
*/
public
class TestThread
extends Thread {
private MyThreadLocal tlt =
new MyThreadLocal();
public TestThread(MyThreadLocal tlt) {
this.tlt = tlt;
}
@Override
public
void run() {
System.out.println(
">>>>>:" + tlt);
for (
int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName() +
"\t" +tlt.getBean()+
"\t"+tlt.getBean().showinfo());
}
}
}
而後運行測試:
>>>>>:MyThreadLocal{tl=com.lavasoft.test2.MyThreadLocal$1@1de3f2d}
>>>>>:MyThreadLocal{tl=com.lavasoft.test2.MyThreadLocal$1@1de3f2d}
>>>>>:MyThreadLocal{tl=com.lavasoft.test2.MyThreadLocal$1@1de3f2d}
>>>>>:MyThreadLocal{tl=com.lavasoft.test2.MyThreadLocal$1@1de3f2d}
Thread-1 com.lavasoft.test2.Bean@291aff Bean{id='0', name='none'}
Thread-2 com.lavasoft.test2.Bean@fe64b9 Bean{id='0', name='none'}
Thread-3 com.lavasoft.test2.Bean@186db54 Bean{id='0', name='none'}
Thread-2 com.lavasoft.test2.Bean@fe64b9 Bean{id='0', name='none'}
Thread-2 com.lavasoft.test2.Bean@fe64b9 Bean{id='0', name='none'}
Thread-0 com.lavasoft.test2.Bean@291aff Bean{id='0', name='none'}
Thread-3 com.lavasoft.test2.Bean@186db54 Bean{id='0', name='none'}
Thread-3 com.lavasoft.test2.Bean@186db54 Bean{id='0', name='none'}
Thread-1 com.lavasoft.test2.Bean@291aff Bean{id='0', name='none'}
Thread-0 com.lavasoft.test2.Bean@291aff Bean{id='0', name='none'}
Thread-0 com.lavasoft.test2.Bean@291aff Bean{id='0', name='none'}
Thread-1 com.lavasoft.test2.Bean@291aff Bean{id='0', name='none'}
Process finished with exit code 0
從打印結果很清楚的看到,MyThreadLocal的tlt對象的確是一個,tlt對象裏的ThreadLocal的tl對象也是一個,可是,將t1t給每一個線程用的時候,線程會從新建立Bean對象加入到ThreadLocal的Map中去使用。