java : spawning new thread is causing original thread to halt

java, multithreading

Solution

You want:

listen.start();

not

listen.run();

Also the preferred way of doing this since Java 5 is to use an `ExecutorService`:

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

and when you want to stop it:

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

or simply:

exec.shutdownNow();

Problem

I have the following code in which I spawn a thread listen which is supposed to constantly listen to any incoming TCP messages, after this thread is run I want the main thread to be used for sending messages but as soon as I initiate listen.run() it seems that main thread does not run any further. I want it to continue to run the while loop but it never reaches it. ``` 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(); } } ``` }

Original source