java currenthread,在Java中使用Thread.currentThread().join()

Java中Thread.currentThread().join()的作用
博客围绕Java代码中Thread.currentThread().join()的使用展开。作者对其作用存疑,认为会使当前线程(主线程)阻塞并死锁。解决方案指出,该语句会让当前线程永久阻塞,防止主线程在服务器启动后立即退出,也可用Thread.sleep(Long.MAX_VALUE)替代。

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) {

//

}

}

}

I understand what is going on apart from the use of Thread.currentThread().join();.

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() 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.

Without that line, the main method would exit right after the server is started.

An alternative would have been to use Thread.sleep(Long.MAX_VALUE);.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值