关于java集合线程安全的一个问题
package thread;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;public class ConcurrentHashMapTest{ Map<String, String> map = new ConcurrentHashMap<String, String>(); /** * 添加 */ public void initMap() { for (int i = 0; i < 10000; i++) { map.put("" + i, "" + i); } } /** * 查询 */ public Map<String, String> getMap() { try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } return map; } public String getValue(String key) { try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } return map.get(key); } public static void main(String[] args) { ConcurrentHashMapTest mapTest = new ConcurrentHashMapTest(); // 初始化 new TestThread(mapTest).start(); // 查询 // System.out.println(mapTest.getValue("9999")); // 查询 System.out.println(mapTest.getMap().size()); }}/** * 测试线程类 */class TestThread extends Thread{ ConcurrentHashMapTest mapTest = null; public TestThread(ConcurrentHashMapTest _mapTest) { this.mapTest = _mapTest; } /** * */ @Override public void run() { mapTest.initMap(); }}class TestThread2 extends Thread{ ConcurrentHashMapTest mapTest = null; public TestThread2(ConcurrentHashMapTest _mapTest) { this.mapTest = _mapTest; } /** * */ @Override public void run() { mapTest.getMap(); }} /** * 添加 */ public void initMap() { synchronized (map) { for (int i = 0; i < 10000; i++) { map.put("" + i, "" + i); } } } /** * 查询 */ public Map<String, String> getMap() { try { // 让其它线程先持有map的锁 Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (map) { return map; } }class Handler { void handle(); ... }class X { private final CopyOnWriteArraySet<Handler> handlers = new CopyOnWriteArraySet<Handler>(); public void addHandler(Handler h) { handlers.add(h); } private long internalState; private synchronized void changeState() { internalState = ...; } public void update() { changeState(); for (Handler handler : handlers) handler.handle(); } }