当我想关闭服务器时,我需要关闭阻塞线程的Selector。所以,我从主线程中调用selector.close()
,这有助于解除阻塞selector.select();
但是选择器不会抛出{I}我想的异常{/ p}}:
ClosedSelectorException
但它会在后面的行中抛出异常:
while (true) {
try {
// Blocks until a 'socket' is ready registered with selector is ready.
selector.select();
}
catch (ClosedSelectorException ex) {
// Never reached?
ex.printStackTrace();
}
catch (IOException ex) {
// Never reached?
ex.printStackTrace();
}
// ...
所以我想做两件事:
Set<SelectionKey> readyKeys = selector.selectedKeys();
中断并让线程停止。我应该使用布尔标志,中断线程,还是从循环中断?
答案 0 :(得分:1)
所以我想做两件事:
当select()取消阻止时,检测选择器是否已关闭。 (可能的?)
之后我想要从while(真实)中断并让线程 停止。
如果您查看Selector
中close方法的文档,您会看到close
方法调用wakeup
方法会调用Selector
当前Selector
(如果等待)立即返回。
如果您查看selector.isOpen()
的文档,您会看到它有一个名为isOpen的方法。
public abstract boolean isOpen()
判断此选择器是否已打开。
您需要做的就是在调用selector.select()
后立即检查break
是否返回false,如果返回false,则只检查selector
。您还应移动使用try-catch
块内boolean
的任何代码。没有必要单独的 try {
// Blocks until a 'socket' is ready registered with selector is ready.
selector.select();
if(!selector.isOpen()) {
break;//graceful exit since selector was not in use anyway
}
Set<SelectionKey> readyKeys = selector.selectedKeys();
// ...
} catch (ClosedSelectorException ex) {
// selector was closed while being used
ex.printStackTrace();
} catch (IOException ex) {
// some other exception
ex.printStackTrace();
}
标志来实现这一目标。这是修改后的代码的外观:
isOpen
使用selector
的好处是,您现在可以确定您的服务器是否正常关闭(没有打印错误),或者在whie(true)
上的某些活动之间关闭(错误打印) )
这里假设Thread
循环是在identity = np.arange(256, dtype = np.dtype('uint8'))
zeros = np.zeros(256, np.dtype('uint8'))
lut = np.dstack((identity, identity, zeros))
的run方法中定义的。