【发布时间】:2014-12-19 21:55:14
【问题描述】:
我有问题。我正在尝试创建一个与 tcp 服务器通信的线程。我的问题是我需要关闭线程。我怎样才能做到这一点?我尝试了.interrupt、.stop,但没有奏效。
最好的问候
Chat thread = new Chat(socket, reuniao[0], username);
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]);
}
}
}
}
}
}
【问题讨论】:
-
查看answer
标签: java multithreading sockets tcp