请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

init()方法里为什么要通过新开线程的方式添加ServerBootstrapAcceptor

老师您好,问题如标题所示,虽然这段代码上有说明,但是我看得一知半解,它这么做的目的好像是为了确保用户自定义的handler在pipline中的位置比ServerBootstrapAcceptor靠前,但是这一点是怎么保证的呢?

 // We add this handler via the EventLoop as the user may have used a ChannelInitializer as handler.
                // In this case the initChannel(...) method will only be called after this method returns. Because
                // of this we need to ensure we add our handler in a delayed fashion so all the users handler are
                // placed in front of the ServerBootstrapAcceptor.
   ch.eventLoop().execute(new Runnable() {
       @Override
       public void run() {
           pipeline.addLast(new ServerBootstrapAcceptor(
                   currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
       }
   });

正在回答 回答被采纳积分+3

1回答

闪电侠 2020-03-07 12:46:00

因为调用这个方法的线程是用户的线程,如果想要确保用户自定义 handler 都在 ServerBootstrapAcceptor 前面完成,只需要在同步的线程中去完成即可,然后 ServerBootstrapAcceptor 在 reactor 线程中执行,而在 reactor 线程中执行的时间肯定是要比本次同步执行的时机要晚,所以能够保证

1 回复 有任何疑惑可以回复我~
  • 提问者 ice_wolf #1
    不好意思老师,可能基础不是很牢固。同步线程指的是现在调用ch.eventLoop().execute()的这个线程而reactor线程是指去执行添加ServerBootstrapAcceptor的那个线程吗?如果是的话为什么reactor 线程中执行的时间肯定是要比本次同步执行的时机要晚呢?
    回复 有任何疑惑可以回复我~ 2020-03-08 20:59:07
  • 慕妹9150414 回复 提问者 ice_wolf #2
    同步线程指的是现在调用ch.eventLoop().execute()的这个线程而reactor线程是指去执行添加ServerBootstrapAcceptor的那个线程吗?
    
    是的。
    
    如果是的话为什么reactor 线程中执行的时间肯定是要比本次同步执行的时机要晚呢?
    
    因为在下面的代码里,   if (handler != null) 这个语句是先执行的
    
    ```
    p.addLast(new ChannelHandler[]{new ChannelInitializer<Channel>() {
                public void initChannel(Channel ch) throws Exception {
                    final ChannelPipeline pipeline = ch.pipeline();
                    ChannelHandler handler = ServerBootstrap.this.config.handler();
                    if (handler != null) {
                        pipeline.addLast(new ChannelHandler[]{handler});
                    }
    
                    ch.eventLoop().execute(new Runnable() {
                        public void run() {
                            pipeline.addLast(new ChannelHandler[]{new ServerBootstrap.ServerBootstrapAcceptor(currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs)});
                        }
                    });
                }
            }});
    ```
    回复 有任何疑惑可以回复我~ 2021-03-27 04:25:54
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信