假设我有一个像这样的课程:
public class Server {
public static void main(String[] args) {
Map<Integer, ServerThread> registry = Collections.synchronizedMap(new LinkedHashMap<Integer, ServerThread>());
...
while(true) {
Socket socket = serverSocket.accept();
ServerThread serverThread = new ServerThread(id, registry);
registry.put(id, serverThread);
}
}
}
然后:
public class ServerThread extends Thread {
private Map<Integer, ServerThread> registry;
private int id;
public ServerThread(int id, Map<Integer, ServerThread> registry) {
this.id = id;
this.registry = registry;
}
...
private void notify() {
synchronized(registry) {
for(ServerThread serverThread : registry.values()) {
serverThread.callSomePublicMethodOnThread();
}
}
}
}
我只想确保在迭代时
registry
不会被修改。使它成为同步映射是否可以保证这种行为?还是我需要synchronized
语句。同步语句的行为是否会像我期望的那样?谢谢
最佳答案
您需要在循环周围使用synchronized
块。
有关详细信息,请参见JavaDoc。