2011-02-09 48 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