您好我有類定義這樣ThreadLocal的行爲
public class JdbcInterceptor {
private static final JdbcInterceptor instance = new JdbcInterceptor();
private static ThreadLocal<Boolean> dontIntercept = new ThreadLocal<Boolean>();
public static JdbcInterceptor getInstance() {
return instance;
}
public void skipIntercept() {
dontIntercept.set(true);
}
public boolean interrupt() {
boolean di = dontIntercept.get()!=null?dontIntercept.get().booleanValue():false;
if (di) {
dontIntercept.set(false);
}
return di;
}// end interrupt
}// end class
,我這樣做是一些其他的Class1現在
//class1 stuff
JdbcInterceptor.getInstance().skipIntercept();
if(JdbcInterceptor.getInstance().interrupt())
{ // class1 stuff happens
}
我在Class2中做到這一點
//class2 stuff
if(JdbcInterceptor.getInstance().interrupt())
{ // class2 stuff happens
}
現在我有點困惑,我知道class1的東西會發生,因爲我設置了 dontIntercept ThreadLocal。我的疑問是class2的東西是否會發生? 我的邏輯是我只有一個JdbcInterceptor實例,因此在所有調用interrupt()的狀態下都應該有相同的狀態。但是我被告知ThreadLocals對於每個線程都是本地的。我在這裏看到一些衝突。請幫助我。
衝突我的意思是隻有一個類的實例返回成員變量的不同值之間的衝突。 – 2010-01-29 09:05:33
編輯的代碼顯示我如何設置跳到假。 – 2010-01-29 09:19:19
如果這是你的意圖,這不是衝突。 ThreadLocals用於此目的。對於新代碼,由於在class1中執行的值始終設置爲「true」,方法跳過,然後重置爲「false」,所以事件順序不同。使用新代碼沒有理由 - 只需刪除class1中的代碼並刪除class2中的if if即可。 – 2010-01-29 09:48:13