Java 从另一个线程访问线程类的公共静态arrayList';s级
我正在尝试访问Java 从另一个线程访问线程类的公共静态arrayList';s级,java,swing,Java,Swing,我正在尝试访问 public static List<ChatThread> Chat_list of my ChatThread Class 至于客户端类: public class help { public static void main(String[] argv) { new Client("Jerry","Smith").start(); } } 和我的服务器类: public class Server { public static void mai
public static List<ChatThread> Chat_list of my ChatThread Class
至于客户端类:
public class help {
public static void main(String[] argv) {
new Client("Jerry","Smith").start();
}
}
和我的服务器类:
public class Server {
public static void main(String[] args) {
try {
ServerSocket server =new ServerSocket(8888);
Socket sc;
System.out.println("Server Started");
while(true){
sc=server.accept();
System.out.println("New Connection");
new ChatThread(sc).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
用于实例化客户端类的主类:
public class help {
public static void main(String[] argv) {
new Client("Jerry","Smith").start();
}
}
对两个线程之间共享的可变对象的每次访问都必须以同步方式进行。不同步将导致您所看到的可见性和一致性问题 您不应该像那样公开
ArrayList
(即使没有多个线程,公共静态可变对象已经是一种非常糟糕的做法)。相反,您应该将其封装在自己的对象中,并确保每个访问都正确同步
在没有看到任何代码行的情况下,很难给出更具体的建议。是什么让您如此确定它不是空的,并且不包含空元素?显示一些代码,这样我们就可以看到发生了什么。另外,为
NullPointerException
添加堆栈跟踪。您需要(至少)显示访问arraylist的代码以及如何实例化每个相关对象(arraylist和2个线程).我在包含arrayList的类中做了一个测试,它不是空的…我将立即添加代码。必须以同步方式访问两个线程之间共享的可变对象。不同步将导致可见性和一致性问题,正如您所看到的。我已经同步了它,但没有任何变化。我只是在问题中添加了我的代码。请看一看
public class help {
public static void main(String[] argv) {
new Client("Jerry","Smith").start();
}
}