我是java编程的新手,现在我正在尝试创建一个控制台聊天应用程序,它包含两个较小的应用程序 - 服务器和客户端。有关发送消息的应用程序功能是当客户端将消息重定向到所有其他客户端时。 启动服务器和连接客户端不是问题。发送消息的时刻到来时,会出现以下错误:
The thread has been interrupted
java.lang.InterruptedException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:503)
at ChatServer.MessagesSender.getNextMessage(MessagesSender.java:34)
at ChatServer.MessagesSender.run(MessagesSender.java:54)
这是相关代码:
package ChatServer;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
class MessagesSender extends Thread {
private ArrayList<String> messages = new ArrayList<String>();
private Client currentClient;
private PrintWriter writer;
private ClientsProcessor processor;
public MessagesSender(Client currentClient, ClientsProcessor processor) {
this.currentClient = currentClient;
this.processor = processor;
try {
this.writer = new PrintWriter(this.currentClient.clientSocket.getOutputStream());
} catch (IOException e) {
System.err.println("Connection lost");
e.printStackTrace();
}
}
public synchronized void processMessage(String message) {
this.messages.add(message);
this.notify();
}
public synchronized String getNextMessage() {
while (this.messages.size() == 0) {
try {
this.wait();
} catch (InterruptedException e) {
System.err.println("The thread has been interrupted");
e.printStackTrace();
}
}
String nextMessage = this.messages.get(0);
this.messages.remove(0);
return nextMessage;
}
private void sendMessageToCurrentClient(String currentMessage) {
this.writer.println(currentMessage);
this.writer.flush();
}
public void run() {
while (!this.isInterrupted()) {
String currentMessage = this.getNextMessage();
this.sendMessageToCurrentClient(currentMessage);
}
this.currentClient.receiver.interrupt();
this.processor.deleteClient(this.currentClient);
}
}
据我所知,其中一个线程处于等待状态,同时它被打断了。有人可以帮我解决这个问题吗? 提前谢谢了! :)
P上。 S。:这是接收者的代码。
package ChatServer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class MessagesReceiver extends Thread {
private Client currentClient;
private BufferedReader reader;
private ClientsProcessor processor;
public MessagesReceiver(Client currentClient, ClientsProcessor processor) {
this.currentClient = currentClient;
this.processor = processor;
try {
this.reader = new BufferedReader(new InputStreamReader(this.currentClient.clientSocket.getInputStream()));
} catch (IOException e) {
System.err.println("Connection lost");
e.printStackTrace();
}
}
public void run() {
while (!this.isInterrupted()) {
try {
String currentMessage = this.reader.readLine();
if (currentMessage == null) {
break;
}
this.processor.processMessage(this.currentClient, currentMessage);
} catch (IOException e) {
System.err.println("Connection lost");
e.printStackTrace();
}
this.currentClient.sender.interrupt();
this.processor.deleteClient(this.currentClient);
}
}
}