关于java NIO中 Chennal的阻塞在regist方法上的解决办法

自己遇到了,研究了一下网上的帖子和oracle的文档。了解清楚后,发现其实解决方法很简单。

先说下阻塞的原因:Channel的regist方法和Selector的select方法是需要获取相同的监视器。oracle文档关于Selector的select方法有这么一句话:

This method performs a blocking selection operation. It returns only after at least one channel is selected, this selector's wakeup method is invoked, or the current thread is interrupted, whichever comes first.

意思是“该方法执行阻塞选择操作。 只有在选择了至少一个通道,调用此选择器的唤醒方法,或者当前线程被中断(以先到者为准)时,它才会返回。”。因此,当没有任何通道时,除非唤醒或者被中断,否则不会返回,即:不会释放选择器。因此Channel的regist方法就被阻塞住了。

知道了原因,解决起来很简单,用以下3种之一:

1、唤醒:调用Selector的wakeup方法

2、中断:interrupt Selector所在线程

3、在至少调用了一次Channel的regist之后,再调用Selector的select。当然很显然,如果已经注册了一个通道,就不需要再保证这个顺序了。

猜你喜欢

转载自blog.csdn.net/anod/article/details/88365406