假设我有一个这样的类(class):
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
block 。
请参阅JavaDoc了解详情。
关于java - 在这种情况下,同步语句如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3887950/