線程和ThreadLocal的聯合,我有一個聲明如下一些方法:如何用Java
這個類被聲明爲使用ThreadLocal
從容器獲得Service
組件。
public class ThreadContext {
private Connector connector;
private static ThreadLocal threadLocal = new ThreadLocal() {
@Override
protected Connector initialValue() {
Service service =
(Service) Container.getComponentInstanceOfType(Service.class);
Connector connector = service.getConnector();
return connector;
}
};
public static Connector get() {
return Connector threadLocal.get();
}
}
的Connector
是中產階級
public class Connector {
public Collection<Result> search() {
User user = ConversationUser.getCurrent()
}
}
的ConversationUser
聲明使用ThreadLocal
也
public class ConversationUser {
private static ThreadLocal<ConversationUser> current =
new ThreadLocal<ConversationUser>();
public static ConversationUser getCurrent() {
return current.get();//(1)
}
}
然後,我寫了一個線程做如下事情:
Thread thread = null;
thread = new Thread(new Runnable() {
public void run(){
ThreadContext context = new ThreadContext();
Collection<Result> result = context.get().search();//(2)
resultsTemp.put("File", result);
}
});
thread.start();
此線程正常工作,但在第(2)行發生NullPointerException
。 正如我調查該方法獲得返回null在行(1)。
這真的讓我很困惑。我不明白爲什麼會出現這個問題。請給我一些澄清,謝謝。
我想回答你的問題,但我發現它太混亂。你的例子中有多個編譯錯誤,而且看起來不完整。由於'search'調用'getCurrent',執行的順序看起來與你描述的不同。 –