ksl*_*ksl 10 java multithreading jersey jersey-2.0
以下代码取自Jersey项目中的示例.看到这里.
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) {
//
}
}
}
Run Code Online (Sandbox Code Playgroud)
我明白除了使用之外发生了什么Thread.currentThread().join();.
我是一个Java新手,我的理解是这将阻止当前线程的执行(在这种情况下,主线程),并有效地使其死锁.即它将导致当前(主)线程阻塞,直到当前(主)线程结束,这将永远不会发生.
它是否正确?如果是这样,为什么会这样?
ass*_*ias 16
Thread.currentThread().join()永远阻止当前线程.在您的示例中,这将阻止main退出,除非程序被终止,例如在Windows上使用CTRL + C.
如果没有该行,主方法将在服务器启动后立即退出.
可以使用另一种方法Thread.sleep(Long.MAX_VALUE);.
一个常见的误解是,如果main线程退出,程序将退出。
仅当没有非守护程序线程正在运行时,才如此。这在这里可能是正确的,但是通常最好恕我直言,使该主线程“等待”非dameon的后台线程,并在无任何事时让主线程退出。我看到开发人员Thread.sleep()陷入了无限循环。等等