Java线程结束/中断退出

SelectorManager包含Reactor(extends Thread)数组,要停止SelectorManager所以要先停掉各个Reactor,查看代码如下:
public synchronized void stop() {
if (!started) {
return;
}
started = false;
for (Reactor reactor : reactorSet) {
reactor.interrupt();
}}
为什么要使用reactor.interrupt()呢?查看Reactor.run()如下代码:
public void run() {
selectorManager.notifyReady();
while (selectorManager.isStarted() && selector.isOpen()) {
try {
int selected = selector.select(wait);
if (selected == 0) {
if (before != -1) {
lookJVMBug(before, selected, wait);
}
关键代码是如下几句:
##
while (selectorManager.isStarted() && selector.isOpen()) {
try {
int selected = selector.select(wait);
##
由于之前在SelectorManager.stop中已经设置started = false,所以在下次循环时Reactor会run结束,但如果该线程正在阻塞执行selector.select(wait),则要等待wait秒才能够返回,如果wait值很大则此线程(Reactor)需要等待很长时间后才能够停止。有没有办法让线程立即响应并退出呢?
我们查看Selector.select文档发现如下:
* <p> This method performs a blocking <a href="#selop">selection
* operation</a>. It returns only after at least one channel is selected,
* this selector's {@link #wakeup wakeup} method is invoked, the current
* thread is interrupted, or the given timeout period expires, whichever
* comes first.
也就是说其实Selector.select方法是响应线程中断的,所以“reactor.interrupt();”后,Reactor线程执行“selector.select(wait);”时会立即返回的。
总结:在某些情况下,必须通过中断(Thread.interrupt())使阻塞的线程中断并返回正常逻辑。 如下所示:
class SessionMonitor extends Thread {
public SessionMonitor() {
this.setName("Heal-Session-Thread");
}
@Override
public void run() {
while (MemcachedConnector.this.isStarted() && MemcachedConnector.this.enableHealSession) {
ReconnectRequest request = null;
try {
request = MemcachedConnector.this.waitingQueue.take();
。。。。。。
} catch (InterruptedException e) {
// ignore,check status
} catch (Exception e) {
log.error("SessionMonitor connect error", e);
this.rescheduleConnectRequest(request);
}
此代码通过MemcachedConnector.this.isStarted()判断是否结束线程。但程序逻辑可能会阻塞在request = MemcachedConnector.this.waitingQueue.take();无法返回。所以需要通过中断线程(this.sessionMonitor.interrupt();)让waitingQueue.take()中断并抛出异常,run()截获异常不做任何处理,使逻辑流转到MemcachedConnector.this.isStarted()判断失败并退出线程。
##
代码详见:com.google.code.yanf4j.nio.impl包
##
 
 

猜你喜欢

转载自murray2081.iteye.com/blog/2236543