由于Netty的NioEventLoop线程被包装成了FastThreadLocalThread线程,同时,NioEventLoop线程的状态由它自身管理,因此每个NioEventLoop线程都需要有一个线程执行器,并且在线程执行前需要通过线程工厂io.netty.util.concurrent.DefaultThreadFactory将其包装成FastThreadLocalThread线程。线程执行器ThreadPerTaskExecutor与DefaultThreadFactory的newThread()方法的代码解读如下:
查看代码 public void execute(Runnable command) { //调用线程工厂类的newThread包装线程,并且启动,等待线程调度。 threadFactory.newThread(command).start(); } public Thread newThread(Runnable r) { //包装FastThreadLocalThread线程,线程的前缀名字为NioEventLoopGroup- //服务启动后可以通过Arthas工具查看 Thread t = newThread(FastThreadLocalRunnable.wrap(r), prefix + nextId.incrementAndGet()); try { if (t.isDaemon() != daemon) { t.setDaemon(daemon); } if (t.getPriority() != priority) { t.setPriority(priority); } } catch (Exception ignored) { // Doesn't matter even if failed to set. } return t; } //包装为FastThreadLocalThread线程 protected Thread newThread(Runnable r, String name) { return new FastThreadLocalThread(threadGroup, r, name); }