我正在开发客户端-服务器应用程序,但遇到以下问题。
在一个类(服务器)中,我有一个对名为 client 的 ArrayList 的静态引用和一个静态 getter getClientsArray()。在另一个类(ServerThread)中,我使用相同的ArrayList并成功修改它(添加/删除客户端)。
对于每个客户端,我调用方法 getClientsArray() 并获取该 ArrayList。问题是 Client 类中的 ArrayList 在这里是空的。每次在 ServerThread 中更新它时(客户端连接后)我都会检查它,里面应该有一些东西。
public class Server {
private static ArrayList<User> clients = new ArrayList<User>();
public static ArrayList<User> getClientsArray() {
return clients;
}
and somewhere I call: new ServerThread(sock, users).start();
}
public class ServerThread extends Thread {
private ArrayList<User> users;
public ServerThread(Socket client, ArrayList<User> users) {
this.client = client;
this.users = users;
}
if I modify users in this class, the changes will occur
}
public class Client extends JFrame {
private ArrayList<User> users;
public Client() {
initGraphics();
users = Server.getClientsArray();
System.out.println(users.size()); <- This line always writes 0!!
}
}
最佳答案
Brian Goetz 在JCIP 中定义了一条简单的规则。 :
If multiple threads access the same mutable state variable without appropriate synchronization, your program is broken.
您拥有客户端
可变状态,并且您没有使用任何同步对其访问的方法。
关于java - 静态ArrayList不会在另一个类中修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16408662/