EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
我们可以看下NioEventLoopGroup
的类继承结构情况,如下所示:
从上图可知,NioEventLoopGroup
实现了ScheduledExecutorService
接口,因此它可以实现定时任务相关的功能。同时它还继承了SingleThreadEventExecutor
类,从类名可以看出,这是一个单线程的线程执行器。在Netty
中,通过NioEventLoopGroup
的创建来达到创建NioEventLoop
的目的。通过有参参数构建NioEventLoopGroup
对象,实际调用的是MultithreadEventExecutorGroup
的构造方法,如下所示:
protected MultithreadEventExecutorGroup(int nThreads, Executor executor,
EventExecutorChooserFactory chooserFactory, Object… args) {
if (nThreads <= 0) {
throw new IllegalArgumentException(String.format(“nThreads: %d (expected: > 0)”, nThreads));
}
if (executor == null) {
//ewDefaultThreadFactory()会创建一个线程工厂,该线程工厂的作用就是用来创建线程,同时给线程设置名称:nioEventLoop-1-XX
executor = new ThreadPerTaskExecutor(newDefaultThreadFactory());
}
// 根据传进来的线程数,来创建指定大小的数组大小,这个数组就是用来存放NioEventLoop对象实例
children = new EventExecutor[nThreads];
for (int i = 0; i < nThreads; i ++) {
//异常标志
boolean success = false;
try {
创建nThreads个nioEventLoop保存到children数组中
children[i] = newChild(executor, args);
success = true;
} catch (Exception e) {
// TODO: Think about if this is a good exception type
throw new IllegalStateException(“failed to create a child event loop”, e);
} finally {
//异常处理
if (!success) {
for (int j = 0; j < i; j ++) {