如果线程在run()完成或有异常时死亡,为什么我的日志会不断添加数字。例如,我有一个线程,在每个循环迭代中打开一个新线程并通过套接字发送一些东西。我的问题,线程正在消亡吗?
class otherClass implements Runnable {
private static Logger logger = LogManager.getLogger(otherClass.class);
String dir_dest = "localhost";
Integer port_dest = 8888;
public ServerExecuter(){
Thread miHilo = new Thread(this);
miHilo.start();
}
public void run() {
try {
while (true) {
Socket sock = server.accept();
BufferedReader in= new BufferedReader(new InputStreamReader(miSocket.getInputStream(), "UTF8"));
String msg = in.readLine();
logger.info(msg);
oneClass ex = new oneClass();
if (ex.isClose()) {
sock.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class onClass implements Runnable {
private static Logger logger = LogManager.getLogger(oneClass.class);
private String host = "localhost";
private Integer port = 9999;
public oneClass(){
Thread my_thread = new Thread(this);
my_thread.start();
}
public void run() {
socket = new Socket(host, port);
DataOutputStream out = new DataOutputStream(socket .getOutputStream());
msg = "Hi";
out.writeBytes(msg);
socket.close();
logger.info("thread finish");
}
public boolean isClose() {
return close;
}
public void setClose(boolean close) {
this.close = close;
}
}
我的代码与此类似,它在控制台中打印以下内容:
11:22:50.810 [Thread-2] INFO
11:22:50.811 [Thread-92] INFO
11:22:50.813 [Thread-92] INFO - thread finish
11:22:50.937 [Thread-2] INFO
11:22:50.938 [Thread-93] INFO
11:22:50.947 [Thread-93] INFO - thread finish
答案 0 :(得分:2)
线程名称由ThreadFactory分配。 Java默认使用" Thread-X"其中X是递增的索引。每个新线程都会获得一个新索引。具有循环的线程(线程-2)不会完成/死亡,但其他线程似乎是(如果可以信任日志记录)