forked from JustinSDK/JavaSE6Tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadLocal.java
More file actions
34 lines (27 loc) · 856 Bytes
/
ThreadLocal.java
File metadata and controls
34 lines (27 loc) · 856 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package onlyfun.caterpillar;
import java.util.*;
public class ThreadLocal<T> {
// 取得一個同步化的Map物件
private Map<Thread, T> storage =
Collections.synchronizedMap(new HashMap<Thread, T>());
public T get() {
// 取得目前執行get()方法的執行緒
Thread current = Thread.currentThread();
// 根據執行緒取得執行緒自有的資源
T t = storage.get(current);
// 如果還沒有執行緒專用的資源空間
// 則建立一個新的空間
if(t == null &&
!storage.containsKey(current)) {
t = initialValue();
storage.put(current, t);
}
return t;
}
public void set(T t) {
storage.put(Thread.currentThread(), t);
}
public T initialValue() {
return null;
}
}