我在我的Java应用程序中有一个TCP服务器,它将我的应用程序生成的数据发送到所有连接的客户端。对于每个新的套接字,我都会创建一个新的线程。以下是线程代码。
public void run() {
try {
PrintStream printStream = new PrintStream(socket.getOutputStream(), true);
while (true) {
if (socket.isClosed()) {
break;
}
synchronized (DataSource.getInstance()) {
printStream.println(DataSource.getInstance().getData());
try {
DataSource.getInstance().wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
当新数据可用时,数据生成线程会写入DataSoure
并调用notifyAll()
,以便处理连接的套接字的所有线程都会醒来并将可用数据发送给客户端。
我的问题是,即使客户端断开连接,socket.isClosed()
也会返回true。因此,处理套接字的线程永远不会被终止。
为什么会发生这种情况?如何在客户端断开连接时退出线程?
IOException
。我是正确的吗? - Lahiru Chandima