我有一些声明如下的方法:
此类声明用于从容器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();
该线程正常工作,但发生NullPointerException
在第 (2) 行。正如我调查的那样,该方法在第 (1) 行返回 null。
我真的很困惑。我不明白为什么会出现问题。请给我一些澄清,谢谢。