---
title: "mina netty线程模型"
author: "pengfeifei26"
date: "2018-06-14T15:30:51Z"
tags: []
categories: ["编程语言"]
slug: "mina-netty"
draft: false
lastmod: "2018-06-14T15:30:51Z"
id: 2424976
url: "https://pengfeifei26.iteye.com/blog/2424976"
---

mina相关
https://www.cnblogs.com/moonandstar08/p/5483605.html
https://www.cnblogs.com/wucao/p/4030211.html
http://www.52im.net/forum.php?mod=viewthread&tid=95
https://blog.csdn.net/u012506661/article/details/52694737

netty相关
https://www.cnblogs.com/NewMan13/p/7820534.html
https://my.oschina.net/7001/blog/1480153


```java

单线程模型
 EventLoopGroup bossGroup = new NioEventLoopGroup(1);
 try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup)
         .channel(NioServerSocketChannel.class)
        ......
以上示例中实例化了一个NIOEventLoopGroup，并传入线程数量为1，然后调用ServerBootstrap的group方法绑定线程组，看实现：

    @Override
    public ServerBootstrap group(EventLoopGroup group) {
        return group(group, group);
    }
    public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup) {
        super.group(parentGroup);
        if (childGroup == null) {
            throw new NullPointerException("childGroup");
        }
        if (this.childGroup != null) {
            throw new IllegalStateException("childGroup set already");
        }
        this.childGroup = childGroup;
        return this;
    }
从源码可知，实际仍然绑定了 bossGroup 和 workerGroup，只是都是同一个NioEventLoopGroup实例而已，这样Netty中的acceptor和后续的所有客户端连接的IO操作都是在一个线程中处理，这就相当于Reactor的单线程模型。


多线程模型
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
      ServerBootstrap b = new ServerBootstrap();
      b.group(bossGroup, workerGroup)
       .channel(NioServerSocketChannel.class)
       ......
创建1个线程的bossGroup线程组，这个线程负责处理客户端的连接请求，而workerGroup默认使用处理器个数*2的线程数量来处理I/O操作。这就相当于Reactor的多线程模型。



主从多线程模型
EventLoopGroup bossGroup = new NioEventLoopGroup(4);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
      ServerBootstrap b = new ServerBootstrap();
      b.group(bossGroup, workerGroup)
       .channel(NioServerSocketChannel.class)
       ......


```