在外部线程调用EventLoop或者channel的一些方法的时候,都会调用InEventLoop()方法检查当前线程是否是NioEventloop中的线程,如如果是外部线程,就会将外部线程的的所有操作封装成为一个task,放进EventLoop的MPSCQ里面,然后在NioEventLoop执行过程的第三个部分,这些task会被依次执行样式
以下从服务端bind()方法进入,进入dobind0()方法:
在外部线程执行Executer
private void startThread() {
// 其他代码省略。。。。
this.doStartThread(); // -------------------------》在此方法中启动线程
}
private void doStartThread() {
//这里的executor就是之前的线程创建器:ThreadPerTaskExecutor,
//执行execute方法之后会创建一个FastLocalThread(netty包装的Thread),并执行run();
this.executor.execute( new Runnable() { // -----------------------》进入execute方法源码:
public void run() {
部分代码省略。。。。
}
io.netty.util.concurrent.ingleThreadEventExecutor
public void execute(Runnable task) {
if (task == null) {
throw new NullPointerException("task");
} else {
boolean inEventLoop = this.inEventLoop(); // -------------------->在此处判断当前线程是不是EventLoop中的线程下面继续跟源码。
this.addTask(task); //将次任务将入任务队列
if (!inEventLoop) {
this.startThread();
if (this.isShutdown()) {
boolean reject = false;
try {
if (this.removeTask(task)) {
reject = true;
}
} catch (UnsupportedOperationException var5) {
;
}
if (reject) {
reject();
}
}
}
if (!this.addTaskWakesUp && this.wakesUpForTask(task)) {
this.wakeup(inEventLoop);
}
}
}
io.netty.util.concurrent.SingleThreadEventExecutor
public boolean inEventLoop(Thread thread) {
return thread == this.thread; // 返回的是当前线程是不是EvenetLoop中的线程
}