请指出/给我一个selector.wakeup()的工作示例;两个线程之间的方法.
我试图创建一个简单的程序,其中一个线程正在等待selector.select()方法.第二个线程创建一些套接字并尝试向选择器注册;第一个线程被阻止的位置.
因此我需要使用选择器的唤醒方法,但不知何故第一个线程不会出现阻塞模式.
唤醒方法的javadoc说明:
If another thread is currently blocked
in an invocation of the
Selector.select() or
Selector.select(long) methods then
that invocation will return
immediately.
P.S还有其他一些解决方法;其中一个是选择(超时)但我试图找出错误的位置.
伪代码:
第一线:
static Selector selector = Selector.open();
while(true) {
int n = selectorGlobal.select();
selectorKeySet = selectorGlobal.selectedKeys().iterator();
while (selectorKeySet.hasNext()) {
selectionKey = selectorKeySet.next();
if (selectionKey.isReadable()) {
//do something
}
if(selectionKey.isAcceptable()) {
//accept
}
}
}
第二线:
while (itr.hasNext()) {
data = (String) itr.next();
String IP = data.get(0);
String Port = data.get(1);
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(true);
boolean isConnected = socketChannel.connect(new InetSocketAddress(IP,Port));
ClassName.selector.wakeup();
SelectionKey selectionKey = SelectSockets.registerChannel(ClassName.selector,socketChannel,SelectionKey.OP_READ);
}