2014-06-12 22 views
1

使用Java(最新的截至上週),我想調用一個線程的方法,我已經存儲在一個哈希映射。我想要做到這一點的原因(將線程存儲在地圖或列表中)是我可能想從多個地方調用該線程的方法,並且不希望將數據存儲在MonitorThread中的靜態變量中,以便能夠這樣做。線程的運行方法,其中標識存儲在地圖

private HashMap<String, Thread> threads = new HashMap<String, Thread>(); 

MonitorThread t = new MonitorThread(); 
t.start(); 
threads.put("monitor", t); 

(MonitorThread)(threads.get("monitor")).SendAlert(); 

我在最後一行發現了cannot resolve SendAlert錯誤。爲什麼?

+2

順便說一句,如果這'threads'地圖將是從多線程訪問(包括只讀取它的線程),你不能使用普通的'HashMap' - 它不是線程安全的。你必須把它包裝在'Collections.synchronizedMap'中,或者使用'ConcurrentHashMap'或其他線程安全的地圖。 – yshavit

+0

謝謝yshavit。這隻能從主線程訪問,所以不用擔心...但您的觀察很受歡迎。 ;) – Jon

回答

2

嘗試:

((MonitorThread) threads.get("monitor")).SendAlert(); 

相反。 .運算符的操作順序高於cast。

此外,如在@MarcoAcierno下面的評論所指出的,你可以得到一個ClassCastException,如果你不小心,所以你可能:

if(threads.get("monitor") instanceof MonitorThread) ((MonitorThread) threads.get("monitor")).SendAlert(); 
+1

如果集合將包含MonitorThread,則只需更改集合的類型即可。或者如果你不小心,你會得到一個ClassCastException。 –

+0

@MarcoAcierno的確。好點子。 –

+0

這樣做的伎倆......認爲它必須是簡單的......或愚蠢的。大聲笑地圖將包含幾個不同的線程類,所以我只是要小心。謝謝! – Jon