gpt4 book ai didi

java - 枚举的 HashMap 作为键

转载 作者:行者123 更新时间:2023-12-04 20:40:55 25 4
gpt4 key购买 nike

我之前也发过类似的问题。我的疑惑也得到了澄清。但我仍然需要更多东西。 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();
}
}

最佳答案

我怀疑您只是在寻找添加到每个枚举中的静态 values() 方法:

for (ThreadpoolName poolName : ThreadpoolName.getValues())

或者,您可以使用 EnumSet.allOf():

for (ThreadpoolName poolName : EnumSet.allOf(ThreadpoolName.class))

(正如 Bozho 所说,EnumMap 是一个不错的选择。您仍然需要遍历枚举值。)

关于java - 枚举的 HashMap 作为键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4944089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com