我有一个问题。我正在尝试创建一个线程用于与 tcp 服务器通信。我的问题是我需要关闭线程。我怎样才能做到这一点?我尝试了.interrupt、.stop,但没有用。
最诚挚的问候
聊天线程 = new Chat(socket, reuniao[0], 用户名);
public class Chat implements Runnable{
Socket socket;
boolean corre;
String reuniao, username;
BufferedReader input;
PrintWriter out;
Scanner sc;
public Chat(Socket socket, String reuniao, String username) {
this.socket = socket;
this.reuniao = reuniao;
this.username = username;
corre = true;
new Thread(this, "").start();
}
@Override
public void run() {
sc = new Scanner(System.in);
try {
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
out = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String answer = null;
out.println("Download Chat#"+reuniao);
try {
answer = input.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("I'm ready!");
ArrayList< String > salaChat = new ArrayList< String >();
String [] chatCompleto = answer.split("#");
for(int i = 0; i < chatCompleto.length; i++){
salaChat.add(chatCompleto[i]);
System.out.println(chatCompleto[i]);
}
while(!Thread.currentThread().isInterrupted()){
if(corre == false) return;
out.println("Download Chat#"+reuniao);
try {
answer = input.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String [] temp = answer.split("#");
for(int i = 0; i < temp.length; i++){
int testa = 0;
for(int j = 0; j < salaChat.size(); j++){
if(temp[i].equals(salaChat.get(j))){
testa = 1;
}
}
if(testa == 0){
salaChat.add(temp[i]);
String [] aux = temp[i].split(":");
if(!username.equals(aux[0]) && temp[i] != null){
System.out.println(temp[i]);
}
}
}
}
}
}
最佳答案
在每个线程中,都有一个中断标志。
你的while
条件很好。
所以你能做的是,
while(!Thread.currentThread().isInterrupted()) {
/* Interrupt the current thread if socket connection is broken.
This will interrupt the thread and the condition in the while loop will become false.
Hence, your loop will exit normally. */
if(socket.isClosed())
Thread.currentThread().interrupt();
}
循环正常退出后,run()
方法将被完全执行,您的线程将自动进入死亡状态
。所以你不需要明确地杀死它。
关于java - java中如何停止或杀死一个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26541511/