java : spawning new thread is causing original thread to halt

标签 java multithreading

我有以下代码,其中我生成一个线程监听,该线程监听应该不断监听任何传入的 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/

相关文章:

java - 烦人的 JSON 解析错误索引 2 超出范围

c# - UWP 从异步工作线程更新 UI

java - 链式 react 破砖

java - Gradle Spring Boot依赖关系:包含为bootRun/排除为bootJar

java - 通知给出 IllegalMonitorStateException

java - 有没有什么情况我应该更喜欢 'volatile' 而不是独占同步?

java - 在 Rx Observable 事务中使用 Realm 调用时,如何防止 Realm 线程问题?

c++ - 将函数传递给新线程时编译器错误?

java - jBPM:在java类或BPMN中声明流程变量

java - 如何读取输入的每一行并按排序顺序输出?