关于Thread.currentThread()问题
来源:4-6 NioEventLoop的启动

慕粉3520842
2018-06-30
public static void main(String args[]){ start(); } public static void start(){ NioEventLoopGroup boss = new NioEventLoopGroup(1); NioEventLoopGroup worker = new NioEventLoopGroup(); try{ ServerBootstrap boot = new ServerBootstrap(); boot.group(boss, worker); boot.channel(NioServerSocketChannel.class); boot.handler(new ChannelHandler(){ public void handlerAdded(final ChannelHandlerContext ctx) throws Exception { System.out.println("---------handlerAdded-----------"); new Thread(new Runnable(){ public void run() { System.out.println(Thread.currentThread().getName()); ctx.executor().execute(new Runnable(){ public void run() { System.out.println("-------------"+Thread.currentThread().getName()); } }); } }).start(); } public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { System.out.println("---------handlerRemoved-----------"); } public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("---------exceptionCaught-----------"); } }); boot.childHandler(new ChannelHandler(){ public void handlerAdded(ChannelHandlerContext ctx) throws Exception { System.out.println("---------handlerAdded-----------"); } public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { System.out.println("---------handlerRemoved-----------"); } public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("---------exceptionCaught-----------"); } }); ChannelFuture f = boot.bind(8894).sync(); Channel channel = f.channel(); channel.closeFuture().sync(); channel.eventLoop().execute(new Runnable(){ public void run() { System.out.println(Thread.currentThread().getName()); } }); }catch(Exception e){ e.printStackTrace(); } }
运行结果为
---------handlerAdded-----------
Thread-1
-------------nioEventLoopGroup-2-1
为什么是这样一个结果nioEventLoopGroup-2-1代表什么啊。另外SingleThreadEventExecutor,即NioEventLoop不是一个线程池吗,为什么还要引进一个ThreadPerTaskExecutor,吧启动一个线程交给他呢。
2回答
-
闪电侠
2018-07-01
NioEventLoop是和线程对应的哦,NioEventLoopGroup和线程池对应,ThreadPerTaskExecutor用于创建NioEventLoop包含的线程,这样做是为了做到线程的创建和执行解耦,一个组件负责创建(ThreadPerTaskExecutor
),一个组件负责维护线程变量以判断执行NioEventLoop对应的方法是外部线程还是本线程00 -
闪电侠
2018-07-01
关于线程命名,可以参考 我的这篇文章https://www.jianshu.com/p/512e983eedf5 里面的线程命名这一小节哦,关于为什么是这样的结果,下面是解释
boot.childHandler只有在新连接接入的时候才会执行里面的回调,因此,可以忽略这里面的输出
第一个handlerAdded是在boot.handler里面的handler回调触发的(在调用boot.bind之后),服务端channel的pipeline被添加一个handler之后会回调到handlerAdded方法,所以这里就输出了
handlerAdded方法在输出第一条消息之后,在new Thread之后输出第二条消息
boot.bind(8894).sync()结束之后,调用channel.eventLoop().execute方法,在回调里面输出的第三条消息,对应的线程是boss
以上暂时看不懂没关系,等后面课程学完了,然后反复复习和调试会弄明白的
00
相似问题