你如何在一行中挂起Java中的一个线程?

一行我的意思是每行最多100个字符。

(我基本上需要这个来保持程序活着。主线程注册在不同的线程中运行的回调监听器。我只需要主要的一个永久挂起并让其他线程完成他们的工作)

 synchronized(this) { while (true) { this.wait(); } } 

(感谢Carlos Heuberger。上面代码中省略了exception处理)

这将使当前线程在当前类的监视器上等待,直到有人调用notify()或永远。

Thread.sleep(Long.MAX_VALUE);

好的,所以它不是永远的,但谈论很长一段时间:)

使用执行者。 通过使用方法shutdown(),您将强制执行程序等待所有线程完成。

使用CountDownLatch,您可以等到计数下降到0,如果您确保它永远不会倒计时,可能只有当它需要结束时。 (这也导致0%cpu,与将永远运行的循环相反,并且使用join(),当所有其他线程完成时,您的应用程序仍将完成,执行程序的选项更好,但也将在所有执行任务时结束完成了)

您可以使用thread.join等待所有线程。

这是一个单行的解决方案,因为您只需要添加一个额外的行。 (您必须添加synchronized并将throws InterruptedExceptionmain声明中。)此外,它不需要访问,甚至不需要知道您正在使用的库中的线程。

 public static synchronized void main(String[] args) throws InterruptedException{ ... YourMainClass.class.wait(); // wait forever } 

它假设您永远不会在主类上调用notify ,并且如果遇到InterruptedException则要退出。 (如果你真的想要防止这种情况,你可以在wait线周围添加一段while (true) { ... } 。)

 public static void main(String[] args) { Thread t = new Thread() { @Override public void run() { try { while (true) { Thread.sleep(1000); } } catch (InterruptedException e) { } } }; t.setDaemon(false); t.start(); } 

while(true){Thread.sleep(1000); }

 for(;;); 

但悬挂线程的可能性非常小。 相反,您应该考虑加入其他线程等选项。