0

是否可以在 Java 中的 NIO 选择器上接收周期性的通用事件?在boost::asio我之前使用过deadline_timer

例如,我想在选择器正在运行的同一个线程上每秒调用一次函数,独立于选择器上活动套接字的负载量(除了特殊情况,例如花费超过一秒来处理传入套接字信息)。

4

1 回答 1

1

像这样的东西可能会起作用:

private final BlockingQueue<YourFunction> queue = ...

public void run() {
    while(!queue.isEmpty()) {
        queue.poll().performAction();
    }

    selector.select();

    Iterator<SelectionKey> itr = selector.selectedKeys().iterator();
    while(itr.hasNext()) {
        // etc...
    }
}

public static void main(String[] args) {
    Timer t = new Timer(name, daemon);
    t.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            queue.add(new YourFunction());
            selector.wakeup();
        }
    }, 0, 1000);
}
于 2012-05-01T01:37:37.573 回答