首页 > 其他分享 >9.NIO-多线程work轮询

9.NIO-多线程work轮询

时间:2022-10-12 13:45:40浏览次数:48  
标签:workSelector register 轮询 work iter sc new 多线程 workers

1.4.5、多线程多work轮询
@Slf4j
public class ThreadServerWorks {
    public static void main(String[] args) throws IOException, InterruptedException {
        Thread.currentThread().setName("boss thread");
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);

        Selector bossSelector = Selector.open();
        ssc.register(bossSelector, SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(50001));

        Worker[] workers = new Worker[2];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker("work thread-" + i);
        }

        AtomicInteger index = new AtomicInteger();
        while (true) {
            bossSelector.select();
            Iterator<SelectionKey> iter = bossSelector.selectedKeys().iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                iter.remove();
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    log.debug("connected...{}", sc.getRemoteAddress());
                    //关联selector
                    log.debug("before register...{}", sc.getRemoteAddress());
                    //轮询
                    workers[index.getAndIncrement() % workers.length].register(sc);

                    log.debug("after register...{}", sc.getRemoteAddress());
                }
            }
        }
    }

    @Data
    static class Worker implements Runnable {
        private String name;
        private Selector workSelector;
        private volatile boolean flag = false;


        public Worker(String name) {
            this.name = name;
        }

        //初始化线程和selector

        public void register(SocketChannel sc) throws IOException {
            if (!flag) {
                workSelector = Selector.open();
                new Thread(this, name).start();
                flag = true;
            }
            workSelector.wakeup();//唤醒select方法
            sc.register(workSelector, SelectionKey.OP_READ, null);
        }

        @Override
        public void run() {
            while (true) {
                try {
                    workSelector.select();

                    Iterator<SelectionKey> iter = workSelector.selectedKeys().iterator();
                    while (iter.hasNext()) {
                        SelectionKey key = iter.next();
                        iter.remove();
                        if (key.isReadable()) {
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel sc = (SocketChannel) key.channel();
                            log.debug("read...{}", sc.getRemoteAddress());
                            sc.read(buffer);
                            buffer.flip();
                            ByteBufferUtil.debugAll(buffer);
                        }
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

标签:workSelector,register,轮询,work,iter,sc,new,多线程,workers
From: https://www.cnblogs.com/jpymll/p/16784236.html

相关文章