我之前也發佈過類似的問題。我也澄清了我的疑惑。但我仍然需要更多東西。 HashMap將使用枚舉對象作爲鍵和線程池實例作爲值進行初始化。我很困惑,如何初始化每個對象的HashMap中被調用其他一些過程..To明確: 我的程序,MyThreadpoolExcecutorPgm.java初始化一個HashMap 我Progran AdditionHandler.java通過傳遞ThreadpoolName請求線程HashMap中(ENUM)。我得到「沒有從HashMap可用的線程」消息。請幫助我。
下面給出的是我的代碼:枚舉的HashMap作爲密鑰
public class MyThreadpoolExcecutorPgm {
enum ThreadpoolName {
DR, BR, SV, MISCELLENEOUS;
}
private static String threadName;
private static HashMap<ThreadpoolName, ThreadPoolExecutor>
threadpoolExecutorHash;
public MyThreadpoolExcecutorPgm(String p_threadName) {
threadName = p_threadName;
}
public static void fillthreadpoolExecutorHash() {
int poolsize = 3;
int maxpoolsize = 3;
long keepAliveTime = 10;
ThreadPoolExecutor tp = null;
threadpoolExecutorHash = new HashMap<ThreadpoolName, ThreadPoolExecutor>();
for (ThreadpoolName poolName : ThreadpoolName.) // failing to implement
{
tp = new ThreadPoolExecutor(poolsize, maxpoolsize, keepAliveTime,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(5));
threadpoolExecutorHash.put(poolName, tp);
}
}
public static ThreadPoolExecutor getThreadpoolExcecutor(
ThreadpoolName poolName) {
ThreadPoolExecutor thread = null;
if (threadpoolExecutorHash != null && poolName != null) {
thread = threadpoolExecutorHash.get(poolName);
} else {
System.out.println("No thread available from HashMap");
}
return thread;
}
}
AdditionHandler.java
public class AdditionHandler{
public void handle() {
AddProcess setObj = new AddProcess(5, 20);
ThreadPoolExecutor tpe = null;
ThreadpoolName poolName =ThreadpoolName.DR; //i am using my enum
tpe = MyThreadpoolExcecutorPgm.getThreadpoolExcecutor(poolName);
tpe.execute(setObj);
}
public static void main(String[] args) {
AdditionHandler obj = new AdditionHandler();
obj.handle();
}
}
感謝很多朋友....不過還是我得到「可從HashMap中尚無主題」同......也是空指針Exception.Any方法來檢查的HashMap是如何得到填補了..? – vidhya 2011-02-09 13:37:53
@vidhya:請發佈一個簡短的*完整的*程序來演示這個問題。大概你會得到NullPointerException,因爲你從getThreadpoolExcecutor返回一個空引用。至於你爲什麼看到「HashMap中沒有可用的線程」 - 這個消息是誤導性的,因爲它意味着其他的threadpoolExecutorHash爲null或者poolName爲null。找出哪個。 – 2011-02-09 13:40:47