// 如果为null,则使用netty默认的ThreadPerTaskExecutor和默认的线程工厂 if (executor == null) { executor = new ThreadPerTaskExecutor(newDefaultThreadFactory()); } // 根据线程数创建EventExecutor数组,EventExecutor真实类型为NioEventLoop children = new EventExecutor[nThreads];
// 初始化线程组 for (int i = 0; i < nThreads; i ++) { boolean success = false; try { // 创建NioEventLoop // newChild 代码逻辑 // EventLoopTaskQueueFactory queueFactory = args.length == 4 ? (EventLoopTaskQueueFactory) args[3] : null; // return new NioEventLoop(this, executor, (SelectorProvider) args[0], //((SelectStrategyFactory) args[1]).newSelectStrategy(), (RejectedExecutionHandler) args[2], queueFactory); children[i] = newChild(executor, args); success = true; } catch (Exception e) { // TODO: Think about if this is a good exception type thrownew IllegalStateException("failed to create a child event loop", e); } finally { // 如果创建失败,则关闭该NioEventLoop if (!success) { for (int j = 0; j < i; j ++) { children[j].shutdownGracefully(); }
for (int j = 0; j < i; j ++) { EventExecutor e = children[j]; try { while (!e.isTerminated()) { e.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS); } } catch (InterruptedException interrupted) { // Let the caller handle the interruption. Thread.currentThread().interrupt(); break; } } } } }
chooser = chooserFactory.newChooser(children);
final FutureListener<Object> terminationListener = new FutureListener<Object>() { @Override publicvoidoperationComplete(Future<Object> future)throws Exception { if (terminatedChildren.incrementAndGet() == children.length) { terminationFuture.setSuccess(null); } } }; // 添加关闭监听器 for (EventExecutor e: children) { e.terminationFuture().addListener(terminationListener); }