gpt4 book ai didi

java - ArrayList 不能在线程中工作

转载 作者:行者123 更新时间:2023-12-01 20:06:37 24 4
gpt4 key购买 nike

我正在使用一个新线程来搜索服务器,并且不会在其他类(例如 Graphics 等)中造成任何滞后。而且我发现了 .add() 方法服务器ArrayList不起作用,甚至servers.size()在新线程中也不起作用。您知道发生了什么以及如何解决这个问题吗?

ArrayList<String> findServers(int howMany){
ArrayList<String> servers = new ArrayList<>();
Main.chatGraphics.log("<font face='arial' color='yellow'>Searching for servers...</font>");
Main.chatGraphics.msgInputTF.setText("Wait...");
Main.chatGraphics.msgInputTF.setEnabled(false);
new Thread(() -> {
Socket newSocket;
for (int i = 2; i < 254; i++){
if (servers.size() >= howMany)
break;
try {
newSocket = new Socket();
InetSocketAddress isa = new InetSocketAddress("192.168.1." + i, Main.DEFAULT_PORT);
if (isa.isUnresolved())
continue;
newSocket.connect(isa, 10);
servers.add(newSocket.getInetAddress().getHostAddress()); // DOESN'T WORK <<
} catch (Exception e) {
e.getStackTrace();
}
}
if (servers.size() == 0) // DOESN'T WORK TOO <<
Main.chatGraphics.log("<font face='arial' color='red'>No available servers</font>");

Main.chatGraphics.msgInputTF.setEnabled(true);
Main.chatGraphics.msgInputTF.setText("");
Main.chatGraphics.msgInputTF.grabFocus();
}).start();

return servers;
}

另外,我对这段代码还有另一个问题:Main.chatGraphics.msgInputTF.setText("Wait...") 不起作用。 setText 方法本身并不能仅在该方法中起作用。我认为发生这种情况是因为 setEnabled(false) 方法紧随其后,但我不确定。你也能帮我解决这个问题吗?

最佳答案

来自Javadoc of ArrayList :

Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:

List list = Collections.synchronizedList(new ArrayList(...));

您有多个线程同时访问此列表:调用该方法的线程和新创建的线程。新创建的线程进行结构修改(它添加到列表中)。因此,您需要外部同步。

ArrayList 包装在 synchronizedList 中。

关于java - ArrayList 不能在线程中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47368754/

24 4 0