java:生成新线程导致原始线程停止
我有下面的代码,其中我生成了一个线程listen,它应该持续侦听任何传入的TCP消息,在该线程运行后,我希望主线程用于发送消息,但一旦我启动listen.run(),主线程似乎就不再运行了。我希望它继续运行while循环,但它永远不会到达它java:生成新线程导致原始线程停止,java,multithreading,Java,Multithreading,我有下面的代码,其中我生成了一个线程listen,它应该持续侦听任何传入的TCP消息,在该线程运行后,我希望主线程用于发送消息,但一旦我启动listen.run(),主线程似乎就不再运行了。我希望它继续运行while循环,但它永远不会到达它 package tcpclient; import java.io.*; import java.net.*; import java.net.UnknownHostException; import java.util.Scanner; import j
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();
不是
由于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();
问题是:
listen.run();
您不能调用
run()
本身!你应该调用<代码> Stand()>代码>,这会产生一个线程,调用<代码> Run()>代码>只需调用一个函数。只是出于好奇,为什么你要在主(中间)中间定义你的新线程?在单独的私有类中定义它不是更好的编码方式吗?
listen.run();