2011-02-09 80 views
2

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

回答

5

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

for (ThreadpoolName poolName : ThreadpoolName.getValues()) 

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

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

(如Bozho说,EnumMap这里是一个很好的选择。您仍然可以通过枚举值需要循环。)

+0

感谢很多朋友....不过还是我得到“可从HashMap中尚无主题”同......也是空指针Exception.Any方法来检查的HashMap是如何得到填补了..? – vidhya 2011-02-09 13:37:53

+0

@vidhya:请发布一个简短的*完整的*程序来演示这个问题。大概你会得到NullPointerException,因为你从getThreadpoolExcecutor返回一个空引用。至于你为什么看到“HashMap中没有可用的线程” - 这个消息是误导性的,因为它意味着其他的threadpoolExecutorHash为null或者poolName为null。找出哪个。 – 2011-02-09 13:40:47

5

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

1

您可以通过一个通过枚举值迭代(按优先顺序排列)

for(Enum value : Enum.values()) 

for(Enum value : EnumSet.allOf(Enum.class)) 

for(Enum value : Enum.class.getEnumConstants()) 

但你也应该使用EnumMap