Java 如何在JVM被杀死之前使线程永远保持活动状态?
我有一个线程,我想一直运行到JVM停止。最好的方法是什么Java 如何在JVM被杀死之前使线程永远保持活动状态?,java,multithreading,Java,Multithreading,我有一个线程,我想一直运行到JVM停止。最好的方法是什么 public void run() { String event = sc.nextLine(); try { queue.put(event); // thread will block here } catch (InterruptedException e) { e.printStackTrace(); } } 必要时添加异常处理。只需添加一个无限循环就可以了
public void run() {
String event = sc.nextLine();
try {
queue.put(event); // thread will block here
} catch (InterruptedException e) {
e.printStackTrace();
}
}
必要时添加异常处理。只需添加一个无限循环就可以了
public void run() {
while(true){
String event = sc.nextLine();
try {
queue.put(event); // thread will block here
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
有一个循环。注意:将循环放在
try
块中,以便其他代码可以中断它。中断是请求线程停止它正在做的任何事情。为了使它保持活动状态,不要返回。在程序存在或最后一个非守护进程线程存在之前,它不会消亡。请注意,在编写该线程时,它将永远循环,不会中断自身,并使JVM实例保持活动状态。您必须发出kill命令才能删除该进程。
public void run() {
while(true){
String event = sc.nextLine();
try {
queue.put(event); // thread will block here
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}