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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3203139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:47:42  来源:igfitidea点击:

How do you hang a thread in Java in one line?

javamultithreading

提问by rui

By one line I mean at most 100 chars per line.

一行是指每行最多 100 个字符。

(I basically need this to keep the program alive. The main thread registers callback listeners that are run in separate threads. I just need the main one to hang forever and let the other threads do their work)

(我基本上需要这个来使程序保持活动状态。主线程注册在单独线程中运行的回调侦听器。我只需要主线程永远挂起并让其他线程完成它们的工作)

回答by Bozho

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

(thanks to Carlos Heuberger. Exception handling omitted in the above code)

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

This will make the current thread wait on the monitor of the current class until someone calls notify(), or forever.

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

回答by krock

There are a few things you could do that would be better than hanging the initial thread forever:

有几件事你可以做,比永远挂起初始线程更好:

  1. Use otherThread.join(). This will cause the current thread you are running in to sleep until the other thread has finished executing.
  2. As @nanda suggests, use ExcecutorService.shutdown()to wait until a pool of threads has finished.
  3. Use otherThread.setDaemon(false)and simply let your initial thread exit. This will set your new threads as user threads. Java will not shut down until the only threads running are daemon threads.
  1. 使用otherThread.join(). 这将导致您正在运行的当前线程休眠,直到另一个线程完成执行。
  2. 正如@nanda 建议的那样,使用ExecutorService.shutdown()等待线程池完成。
  3. 使用otherThread.setDaemon(false)并简单地让您的初始线程退出。这会将您的新线程设置为用户线程。Java 不会关闭,直到唯一运行的线程是守护线程。

回答by Tim Bender

Thread.sleep(Long.MAX_VALUE);

Thread.sleep(Long.MAX_VALUE);

Ok, so it isn't forever, but talk about a really long time :)

好的,所以它不是永远的,但要讨论很长时间:)

回答by nanda

Use executor. By using method shutdown() you'll force the executor to wait until all threads are finished.

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

回答by Redlab

With a CountDownLatchyou can wait untill the count down reached 0, if you make sure it never counts down, maybe only when it needs to end. (This also result in 0% cpu, the opposite of loops that will run forever, and with join() your app will still finish when all other threads finished, The option of the executor is better, but will also end when all executed task have finished)

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

回答by NG.

You can use thread.jointo wait for all of the threads.

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

回答by Eamonn O'Brien-Strain

Here is a solution that is a one-liner, in that you only have to add one extra line. (You do have to add synchronizedand throws InterruptedExceptionto your maindeclaration though.) Also, it does not need access to, or even knowledge of the threads in the library you are using.

这是一种单行解决方案,您只需添加一条额外的行。(不过,您必须将synchronized和添加throws InterruptedException到您的main声明中。)此外,它不需要访问,甚至不需要了解您正在使用的库中的线程。

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

It assumes you will never call notifyon your main class and that you want to exit if you get an InterruptedException. (You can add a while (true) { ... }around the waitline if you really want to guard against that.)

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

回答by Nathan Garabedian

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

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

回答by Steve McLeod

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();
}

回答by Matthew Flaschen

for(;;);

But it's very unlikely that hanging the thread is what you want. Instead, you should consider options like joining on the other threads.

但是,挂线不太可能是您想要的。相反,您应该考虑加入其他线程等选项。