工作要求用Java了,有很多東西要學習.不得不暫時告別一下.net
在看Spring的時候突然想到.net裡面的ThreadStaticAttribute(允許static變數在不同線程不同).
在很多情況下每個執行線程裡面的內容是固定的,比如web環境下servlet的CurrentUser/HttpContext/Session.很多情況下這些變數被想方設法的傳遞到後層類中,造成設計的複雜.
.net中很好的設計方法就是Static: Thread.CurrentPrincipal / HttpContext.Current ....
那麼Java中是否也有類似機制呢?答案是ThreadLocal.
API doc: http://java.sun.com/j2se/1.4.2/docs/api/index.html
DW上Brian Goetz 的文章:http://www-900.ibm.com/developerWorks/cn/java/j-threads/index3.shtml
Brian Goetz 在文章中指出,在jdk1.4中ThreadLocal的效能已經可以不用擔心.
在用法上比.net要複雜,API中的例子比較怪異,這裡是我自己寫的例子:public class Hello implements Runnable{
static class Counter{
int c = 0;
public void Count(){
System.out.println(Thread.currentThread().hashCode() + ": "+ c++);
}
}
private static ThreadLocal counter = new ThreadLocal(){
protected Object initialValue() {return new Counter();}
};
public static Counter Counter(){return (Counter)counter.get();}
public static void main(String[] args)throws Exception {
Hello h = new Hello();
h.run();
new Thread(new Hello()).start();
Thread.sleep(1000L);
h.run();
Counter().Count();
}
public void run() {
Counter().Count();
Counter().Count();
Counter().Count();
}
}
結果:25358555: 0
25358555: 1
25358555: 2
26399554: 0
26399554: 1
26399554: 2
25358555: 3
25358555: 4
25358555: 5
25358555: 6
看樣ThreadLocal工作的很好.請注意ThreadLocal類似一個訪問媒介,get()返回的值是儲存在當前線程中的.
值得注意的是InheritableThreadLocal類,可以使ThreadLocal資料傳遞到子線程中.
另外servlet線程可能會被重新利用,要注意在每個servlet開始時重新初始化.