为什么事件循环使用多个线程?

Why event loop uses more than one thread?

我一直认为异步执行是关于高效的资源利用和线程安全,但今天我运行进入Netty的st运行ge行为。

public class Example {
    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            bootstrap.group(group)
                     .channel(NioServerSocketChannel.class)
                     .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel channel) {
                            channel.pipeline()
                                   .addLast(new ChannelOutboundHandlerAdapter() {
                                        @Override
                                        public void read(ChannelHandlerContext ctx) {
                                            String id = String.valueOf(Thread.currentThread().getId());
                                            ctx.writeAndFlush(Unpooled.wrappedBuffer(id.getBytes(StandardCharsets.UTF_8)))
                                               .addListener(ChannelFutureListener.CLOSE);
                                            }
                                        });
                        }
                    })
                    .bind("localhost", 1234)
                    .sync()
                    .channel()
                    .closeFuture()
                    .syncUninterruptibly();
        } finally {
            group.shutdownGracefully()
                 .syncUninterruptibly();
        }
    }
}

当我第一次连接时,我得到了 16。然后是 17、18、19 等等。每个连接都在一个新线程上执行!为什么?如果是多线程,Netty 有什么意义?

NioEventLoopGroup 使用工作线程来利用多个 CPU 核心。根据 the no-argument constructor javadoc:

NioEventLoopGroup()

Create a new instance using the default number of threads, the default ThreadFactory and the SelectorProvider which is returned by SelectorProvider.provider().

根据 MultithreadEventLoopGroup 的默认线程数将是可用处理器数的两倍:

DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt(
            "io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));

通常,这应该足以使 CPU 饱和,而无需创建大量线程。生成的线程太少,您将无法充分利用 CPU。产生太多,你会浪费大量时间在它们之间进行上下文切换。