用于枚举的HashMap作为键

vid*_*hya 2 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

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

for (ThreadpoolName poolName : ThreadpoolName.getValues())
Run Code Online (Sandbox Code Playgroud)

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

for (ThreadpoolName poolName : EnumSet.allOf(ThreadpoolName.class))
Run Code Online (Sandbox Code Playgroud)

(正如Bozho所说,EnumMap这里是一个很好的选择.你仍然需要遍历枚举值.)


Boz*_*zho 5

首先,你最好使用EnumMap.然后确保在调用方法之前填充了地图.