我希望我的主线程一直运行,因为我有一些监听器将在另一个线程中监听请求/消息,我不希望我的主线程死亡。
哪个更好?
CountDownLatch计数器
public static void main(String[] args) throws InterruptedException {
startListener();
CountDownLatch latch = new CountDownLatch(1);
latch.await();
}
Or While with sleep
public static void main(String[] args) throws InterruptedException {
startListener();
while (true){
Thread.sleep(1000);
}
}
startListeners()
或任何必须在主线程终止之前完成的代码吗? - ernest_kCountDownLatch.await
是一种更复杂的机制,它会等待直到计数器减为0,而Thread.sleep
很少是一个好决定,特别是当它是重复的时候。这两种情况都不好,没有办法停止它们(前者需要在startListener
中传递latch
,后者需要引用主线程才能中断它)。 - Andrew Tobilko