java:产生新线程导致原始线程停止

时间:2010-02-16 01:23:11

标签: 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();
   }


}

}

2 个答案:

答案 0 :(得分:9)

你想:

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();

答案 1 :(得分:3)

问题在于:

listen.run();

你不能自己致电run()!你应该调用start(),这会生成一个线程,调用run()只需调用一个函数。