我必须通过某个端口将一组文件发送到几台计算机。事实是,每次调用发送文件的方法时,都会计算目标数据(地址和端口)。因此,使用循环为每个方法调用创建一个线程,并在方法调用周围加上一个 BindException 的 try-catch 语句来处理程序试图使用已经在使用的端口的情况(不同的目标地址可能通过同一端口接收消息)告诉线程等待几秒钟然后重新启动重试,并继续尝试直到不抛出异常(成功执行传送)。我不知道为什么(尽管当我第一次看到它时我就猜到了),Netbeans 警告我在循环中休眠一个 Thread 对象不是最佳选择。这个链接到另一个 stackoverflow 帖子,看起来很有趣(我从未听说过ThreadPoolExecutor 类)。我一直在阅读该链接和 API 以尝试改进我的程序,但我还不太确定我应该如何在我的程序中应用它。有人可以帮忙吗?
编辑:重要代码:
for (Iterator<String> it = ConnectionsPanel.list.getSelectedValuesList().iterator(); it.hasNext();) {
final String x = it.next();
new Thread() {
@Override
public void run() {
ConnectionsPanel.singleAddVideos(x);
}
}.start();
}
private static void singleAddVideos(String connName) {
String newVideosInfo = "";
for (Iterator<Video> it = ConnectionsPanel.videosToSend.iterator(); it.hasNext();) {
newVideosInfo = newVideosInfo.concat(it.next().toString());
}
try {
MassiveDesktopClient.sendMessage("hi", connName);
if (MassiveDesktopClient.receiveMessage(connName).matches("hello")) {
MassiveDesktopClient.sendMessage(newVideosInfo, connName);
}
} catch (BindException ex) {
MassiveDesktopClient.println("Attempted to use a port which is already being used. Waiting and retrying...", new Exception().getStackTrace()[0].getLineNumber());
try {
Thread.sleep(MassiveDesktopClient.PORT_BUSY_DELAY_SECONDS * 1000);
} catch (InterruptedException ex1) {
JOptionPane.showMessageDialog(null, ex1.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
ConnectionsPanel.singleAddVideos(connName);
return;
}
for (Iterator<Video> it = ConnectionsPanel.videosToSend.iterator(); it.hasNext();) {
try {
MassiveDesktopClient.sendFile(it.next().getAttribute("name"), connName);
} catch (BindException ex) {
MassiveDesktopClient.println("Attempted to use a port which is already being used. Waiting and retrying...", new Exception().getStackTrace()[0].getLineNumber());
try {
Thread.sleep(MassiveDesktopClient.PORT_BUSY_DELAY_SECONDS * 1000);
} catch (InterruptedException ex1) {
JOptionPane.showMessageDialog(null, ex1.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
ConnectionsPanel.singleAddVideos(connName);
return;
}
}
}