我有一个 ArrayList 的套接字,并且我正在使用多个线程。我是否需要将列表声明为 Collections.synchronizedList ,然后每次要迭代列表时调用 synchronized(listName) ?使用 listName.add(socket) 将新套接字添加到列表中怎么样?我还需要同步该呼叫吗?
服务器类
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Server implements Runnable {
private int listenPort;
private int maxClients;
private int clientNumber;
private boolean isRunning;
private ServerSocket listener;
// Synchronize This?
private ArrayList<Client> clients;
public Server(int listenPort, int maxClients) throws IOException {
this.listenPort = listenPort;
this.maxClients = maxClients;
this.clientNumber = 0;
this.isRunning = true;
this.listener = new ServerSocket(
listenPort, maxClients,
InetAddress.getLocalHost()
);
this.clients = new ArrayList<Client>();
}
@Override
public void run() {
while (isRunning) {
try {
Socket socket = listener.accept();
Client client = new Client(socket, ++clientNumber);
clients.add(client);
new Thread(client).start();
} catch (IOException ex) {}
}
}
}