1
java | eventloop 简介
source link: https://benpaodewoniu.github.io/2023/01/23/java187/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
eventloop 简介
姑苏城外一茅屋,万树梅花月满天
eventloop
本质上是一个单线程执行器「同时维护了一个 selector
」,里面有 run
方法处理 channel
上源源不断的 IO
事件。
eventloopgroup
是一组 eventloop
,channel
一般会调用 eventloopgroup
的 reginster
方法来绑定其中一个 eventloop
,后续这个 channel
上的 IO
事件就由此 eventloop
来处理了。
// 1 创建事件循环
EventLoopGroup eventLoopGroup = new NioEventLoopGroup(2); // io 事件、定时任务、普通任务
// EventLoopGroup eventLoopGroup2 = new DefaultEventLoopGroup(); // 定时任务、普通任务
参数可以指定默认线程数,如果不指定,就是线程数 * 2
package com.redisc;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import java.io.IOException;
public class Run {
public static void main(String[] args) throws IOException {
// 1 创建事件循环
EventLoopGroup eventLoopGroup = new NioEventLoopGroup(2); // io 事件、定时任务、普通任务 参数可以指定默认线程数,如果不指定,就是线程数 * 2
// EventLoopGroup eventLoopGroup2 = new DefaultEventLoopGroup(); // 定时任务、普通任务
// 获取下一个循环对象
System.out.println(eventLoopGroup.next());
System.out.println(eventLoopGroup.next());
System.out.println(eventLoopGroup.next());
// 执行普通任务
}
}
io.netty.channel.nio.NioEventLoop@d7b1517
io.netty.channel.nio.NioEventLoop@16c0663d
io.netty.channel.nio.NioEventLoop@d7b1517
可以看到第一个输出和第三个输出的地址是一样的,这是因为,我们就弄了 2
个线程。
package com.redisc;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import java.io.IOException;
public class Run {
public static void main(String[] args) throws IOException {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup(2); // io 事件、定时任务、普通任务 参数可以指定默认线程数,如果不指定,就是线程数 * 2
// 执行普通任务
eventLoopGroup.next().execute(() -> {
System.out.println(123);
});
}
}
package com.redisc;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class Run {
public static void main(String[] args) throws IOException {
// 1 创建事件循环
EventLoopGroup eventLoopGroup = new NioEventLoopGroup(2); // io 事件、定时任务、普通任务 参数可以指定默认线程数,如果不指定,就是线程数 * 2
// 执行定时任务
eventLoopGroup.next().scheduleAtFixedRate(() -> {
System.out.println(1);
}, 0, 1, TimeUnit.SECONDS);
}
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK