在Java中使用Thread.currentThread().join() [英] Use of Thread.currentThread().join() in Java
问题描述
The following code is taken from an example in the Jersey project. See here.
public class App {
private static final URI BASE_URI = URI.create("http://localhost:8080/base/");
public static final String ROOT_PATH = "helloworld";
public static void main(String[] args) {
try {
System.out.println("\"Hello World\" Jersey Example App");
final ResourceConfig resourceConfig = new ResourceConfig(HelloWorldResource.class);
final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, resourceConfig, false);
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
server.shutdownNow();
}
}));
server.start();
System.out.println(String.format("Application started.\nTry out %s%s\nStop the application using CTRL+C",
BASE_URI, ROOT_PATH));
//////////////////////////////
Thread.currentThread().join();
//////////////////////////////
} catch (IOException | InterruptedException ex) {
//
}
}
}
除了使用Thread.currentThread().join();
之外,我还了解发生了什么.
I understand what is going on apart from the use of Thread.currentThread().join();
.
我是Java新手,我的理解是,这将阻止当前线程(在本例中为主线程)的执行,并有效地死锁它.即它将导致当前(主)线程阻塞,直到当前(主)线程完成为止,这将永远不会发生.
I'm a Java newbie and my understanding is that this will block the execution of the current thread (in this case, the main thread), and effectively deadlock it. i.e. it will cause the current (main) thread to block until the current (main) thread finishes, which will never happen.
这是正确的吗?如果是这样,为什么会在那里?
Is this correct? If so, why is it there?
推荐答案
Thread.currentThread().join()
永远阻止当前线程.在您的示例中,除非程序被杀死,否则它会阻止main
退出.在Windows上使用CTRL + C.
Thread.currentThread().join()
blocks the current thread forever. In your example, that prevents the main
from exiting, unless the program is killed, e.g. with CTRL+C on Windows.
如果没有这一行,则在启动服务器后,main方法将立即退出.
Without that line, the main method would exit right after the server is started.
另一种选择是使用Thread.sleep(Long.MAX_VALUE);
.
这篇关于在Java中使用Thread.currentThread().join()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!