java线程执行完关闭窗口,如何实现在执行结束时自动关闭的线程池?

I'm writing a Java client which could theoretically be used in a different environment: Java main(), in a servlet container, or via dependency injection.

The client implements internal connection thread pooling.

The problem with this approach is that users of the client that are unaware of the fact that an internal thread pool is implemented will see his or her application "hang" on shutdown. My users need to know to send a shutdown() message to the library.

I'm wondering if any other alternative approach could be taken that would, on one hand, allow me to start a thread pool for my connections; and, on the other hand, catch some event, perhaps a JVM event, that indicates the JVM is going down, which will allow me to call my shutdown() implementation.

解决方案

Although you can add hooks, as was previous suggested, the problem you're still likely to have is the thread-pool still having active threads.

I believe that if you mark your individual threads as "daemons" (via Thread.setDaemon method) then the JVM will not keep alive if only daemon threads are left.

From the JavaDoc:

Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.

Using this, if your primary non-daemon thread is terminated, the JVM won't "hang-up" because of the other thread running, and this trigger your shutdown hooks without having to explicitly send terminate instructions to the various threads.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值