在这种情况下,同步语句如何工作?

Viv*_*ath 0 java concurrency multithreading synchronization synchronized

假设我有这样一个类:

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);
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

然后:

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();
         }
      }      
   }
}
Run Code Online (Sandbox Code Playgroud)

我只想确保registry在迭代它时不会被修改.使它成为同步映射可以保证这种行为吗?或者我需要synchronized声明.同步语句的行为会像我期望的那样吗?

谢谢

Chr*_*isH 5

你需要synchronized围绕循环的块.

有关详细信息,请参阅JavaDoc.