Java中的垂死线程 [英] Dying thread in java
问题描述
如果线程在run()完成或出现异常时死亡,为什么我的日志会不断增加数字.例如,我有一个线程,每个循环迭代都会打开一个新线程,并通过套接字发送内容.我的问题是,线程快要死了吗?
If thread died when run() finish or when there is an exception, why my log keeps adding numbers. For example, I have a thread that on every loop iteration opens a new thread and send something over a socket. My question, the threads are dying right?
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;
}
}
我的代码大致是这样的,它在控制台中显示以下内容:
My code is roughly like this, and it prints the following in the console:
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
推荐答案
线程名称由ThreadFactory分配. Java默认使用"Thread-X",其中X是递增索引.每个新线程都会获得一个新索引.带有循环的线程(线程2)没有完成/死亡,但其他线程似乎是(如果日志记录可以信任)
The thread name is allocated by the ThreadFactory. Java defaults to using "Thread-X" where X is an incremented index. Each new thread gets a new index. The thread with the loop (Thread-2) doesn't complete/die, but the others appear to be (if the logging can be trusted)
这篇关于Java中的垂死线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!