如何使线程永远保持活动状态,直到 JVM 被杀死



>我有一个线程,我想一直运行它,直到JVM停止。最好的方法是什么?

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();
        }
    }
}
while (true) { runBody(); }

如有必要,添加异常处理。

最新更新