1
如果兩個線程嘗試將(鍵,值)放入同一個映射中傳遞給線程的構造函數。我可能遇到什麼樣的線程問題?由兩個線程併發修改HashMap
public class App {
public static void main(String[] args) throws JMSException {
Map<String, String> map = new HashMap<String, String>();
map.put("5", "fnc");
Thread t1 = new App().new T(map);
Thread t2 = new App().new T(map);
t1.start();
t2.start();
}
class T extends Thread {
private Map<String, String> map;
public T(Map<String, String> map) {
this.map = map;
}
public void run() {
// put 100s of keys in map here
map.put("1", "abc");
// put other keys
}
}
}
對Oracle HashMap實現的併發讀取和寫入操作可能會導致掛起的線程(由於底層實現,很容易使其陷入無限循環)。請參閱http://stackoverflow.com/a/1068213/83695 – andersoj