嗨,有人可以帮助我处理这段代码吗,因为我正在尝试使用 If 语句,但没有工作。我并不是要求为我编写代码,只是向我指出一些东西。
主要问题是,每次有人连接时,都会创建新线程,但是当他关闭聊天框时,线程会保持打开状态,并且无法正常工作。我的意思是有些人自己建立了 10 个联系,其他人都无法聊天。
import java.net.*;
import java.io.*;
public class myServer {
static ServerSocket server;
static Socket client;
static DataInputStream in;
static DataOutputStream out;
static clientThread t[] = new clientThread[10];
public static void main(String[] args) throws IOException {
System.out.println("Starting Server");
server = new ServerSocket(7555);
System.out.println("Started Server");
while (true) {
client = server.accept();
System.out.println("CONNECTION");
out = new DataOutputStream(client.getOutputStream());
out.writeUTF("Welcome to the chat room");
for (int i = 0; i <= 9; i++) {
if (t[i] == null) {
(t[i] = new clientThread(client, t)).start();
break;
}
}
}
}
}
class clientThread extends Thread {
DataInputStream in;
DataOutputStream out;
static String msg;
Socket client = null;
clientThread t[];
public clientThread(Socket client, clientThread[] t) {
this.client = client;
this.t = t;
}
public void run() {
try {
in = new DataInputStream(client.getInputStream());
out = new DataOutputStream(client.getOutputStream());
boolean tru = true;
while (tru) {
msg = in.readUTF();
System.out.println(msg);
for (int i = 0; i <= 9; i++)
if (t[i] != null) {
t[i].out.writeUTF(msg);
System.out.println(t[i]);
}
}
} catch (IOException e) {
}
}
}
最佳答案
您的问题不是线程保持打开状态,而是您没有将客户端线程标记为已完成的机制。即使线程已经退出,t[i]
也不会变成null
。它仍然会引用线程的实例——只是一个“死”线程。
这里有两种解决方法:
在线程退出之前,标记
t[i] = null
(其中i
是当前线程的索引)。请注意,您需要在每个线程中存储i
的值。- 修改
clientThread
并添加private int threadIndex;
作为成员变量。 修改
clientThread
的构造函数并添加threadIndex
作为参数。public clientThread(Socket client, clientThread[] t, int threadIndex) { this.threadIndex=threadIndex; //... }
在
run
的右大括号之前添加synchronized(t){t[this.threadIndex]=null;}
- 修改
使用
Executor
并向其提交您的clientThread
。 Java 的Executor
将为您清理线程。
关于java - 聊天服务器。线程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8670928/