时间轮算法

Netty时间轮

构造方法

1
2
3
4
5
6
7
HashedWheelTimer timer = new HashedWheelTimer(
myThreadFactory, // 线程工厂
100, // tickDuration:时间间隔(单位见下)
TimeUnit.MILLISECONDS, // 单位
512 // 时间轮槽位数(必须是2的幂,越大越精细)
);

负责执行定时任务的work线程~~~~默认~~~~是一个jvm的守护线程(是不是守护线程,取决你传入的ThreadFactory)

~~ 这意味着当 JVM 中只剩下这个线程时,进程会自动退出,不会阻止 JVM 停止。 ~~

1
2
3
HashedWheelTimer timer = new HashedWheelTimer(); // 默认使用守护线程 
使用的是用户线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
private static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;

DefaultThreadFactory() {
@SuppressWarnings("removal")
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}

public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
//!!!!!!!!
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}