gpt4 book ai didi

java : spawning new thread is causing original thread to halt

转载 作者:行者123 更新时间:2023-12-02 08:34:36 25 4
gpt4 key购买 nike

我有以下代码,其中我生成一个线程监听,该线程监听应该不断监听任何传入的 TCP 消息,在该线程运行后,我希望主线程用于发送消息,但一旦我启动监听.run() 似乎主线程不再运行了。我希望它继续运行 while 循环,但它永远不会到达它。

package tcpclient;

import java.io.*;
import java.net.*;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class client {
//instance vars
static Socket cSocket =null;
static PrintWriter out = null;
static BufferedReader in = null;

//server info
static String serverName = null;
static int serverPort = 0;
static String userName=null;

//listening vars
static Thread listen;
static String incoming=null;

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
try {
System.out.println("\n\n\nTCP Chat Client\n\nEnter server name:");
Scanner scan = new Scanner(System.in);

//get server info from user
serverName = scan.nextLine();

System.out.println("\nEnter port number:");
serverPort = Integer.parseInt(scan.nextLine());


System.out.println("\nEnter your username:");
userName = scan.nextLine();

//make connection to server
cSocket = new Socket(serverName, serverPort);
out = new PrintWriter(cSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));

//send username to server
out.println(userName);

//start listening
listen = new Thread(){
@Override
public void run(){
try {
incoming = in.readLine();
while (!(incoming.equals(null))) {
System.out.print(incoming);


incoming = in.readLine();

}
} catch (IOException ex) {
Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
}
}

};
listen.run();
String rcvrname="wefwef";
String message=null;
//start messaging
while(!(rcvrname.equals("exit"))){
System.out.println("Enter reciever name");
out.println(scan.nextLine());
System.out.println("Enter message");
out.println(scan.nextLine());

}
out.close();
in.close();
cSocket.close();

}

catch (UnknownHostException ex) {
System.err.println("\ncan't find that host\n");

}

catch (IOException ex) {
Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
}

finally{
in.close();
out.close();
cSocket.close();
}


}

}

最佳答案

你想要:

listen.start();

不是

listen.run();

自 Java 5 以来,执行此操作的首选方法是使用 ExecutorService:

Runnable listen = new Runnable() {
public void run() { ... }
}
ExecutorService exec = Executors.newSingleThreadExecutor();
exec.submit(listen);

当你想停止它时:

exec.shutdown();
exec.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

或者简单地说:

exec.shutdownNow();

关于java : spawning new thread is causing original thread to halt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2270076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com