我之前也发过了类似的问题。我也澄清了我的怀疑。但我还需要更多东西。将使用枚举对象作为键并将线程池实例作为值来初始化Hashmap。我很困惑如何为其他一些进程调用的每个对象初始化HashMap。要弄清楚: 我的程序MyThreadpoolExcecutorPgm.java初始化一个HashMap 我的Progran AdditionHandler.java通过传递ThreadpoolName(枚举)从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();
}
}
答案 0 :(得分:5)
我怀疑你只是在寻找添加到每个枚举的静态values()
方法:
for (ThreadpoolName poolName : ThreadpoolName.getValues())
或者,您可以使用EnumSet.allOf()
:
for (ThreadpoolName poolName : EnumSet.allOf(ThreadpoolName.class))
(正如Bozho所说,EnumMap
在这里是一个很好的选择。你仍然需要遍历枚举值。)
答案 1 :(得分:5)
首先,您最好使用EnumMap
。然后确保在调用方法之前填充了地图。
答案 2 :(得分:1)
您可以按(按优先级降序排列)
之一迭代枚举值for(Enum value : Enum.values())
for(Enum value : EnumSet.allOf(Enum.class))
for(Enum value : Enum.class.getEnumConstants())
但你也应该使用EnumMap
。