java - 枚举的 HashMap 作为键

标签 java

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

相关文章:

java - JAX-RS UriInfo.getQueryParameters() 返回 UnmodifiableMultivaluedMap

java - 在java中下载图像

java - 为什么 native String getBytes 方法比自定义实现的 getBytesFast 方法慢?

java - MaltParser 1.5 PatternSyntaxException

java - 导入android项目的问题

java - createStoredProcedureQuery 未解决

java - 如何将 Joda-Time DateTime 格式化为仅 mm/dd/yyyy?

java - 镜像无法更新其他组件(MVC)

java - 无法将 .jks 转换为 .pkcs12 : excess private key

java - jdk7u25 是否引入了时区错误?