- 自定义ThreadFactory,便于创建自定义线程
- 自定义ThreadGroup,便于对线程分组管理
ThreadFactory和ThreadGroup封装
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
29
30
31
32
33
34
35
36
37
38
39
40
41
424j
public class CustomThreadFactory implements ThreadFactory {
private AtomicInteger threadNum = new AtomicInteger(1);
private final static String prefix = "Custom-thread-";
public Thread newThread(Runnable r) {
String name = prefix + threadNum.getAndIncrement();
ThreadGroup threadGroup = new CustomThreadGroup("Custom_GROUP");
//非守护进程
threadGroup.setDaemon(false);
//优先执行
threadGroup.setMaxPriority(Thread.MAX_PRIORITY);
Thread thread = new Thread(threadGroup, r, name);
return thread;
}
static class CustomThreadGroup extends ThreadGroup {
public CustomThreadGroup(String name) {
super(name);
}
public CustomThreadGroup(ThreadGroup parent, String name) {
super(parent, name);
}
/**
* 异常处理
*
* @param t
* @param e
*/
public void uncaughtException(Thread t, Throwable e) {
log.error("线程名称:{},异常信息:{},异常栈:{}",
t.getName(), e.getMessage(), e);
}
}
}
ThreadFactory
- ThreadFactory的作用就是提供创建线程的功能的线程工厂
- 它是通过newThread()提供创建线程
- newThread()创建的线程对应的任务是Runnable对象
- 它创建的线程默认都是“非守护线程”而且“线程优先级都是Thread.NORM_PRIORITY”。
ThreadGroup
- 方便地对加入这个线程组的多个线程进行操作。
- 重写uncaughtException()来实现自己的线程运行时异常处理逻辑
- 线程组可以进行复制,快速定位到一个线程
- Thread类的enumerate()方法用于将每个活动线程的线程组及其子组复制到指定的数组中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17ThreadGroup group = Thread.currentThread().getThreadGroup();
ThreadGroup topGroup = group;
// 遍历线程组树,获取根线程组
while (group != null) {
topGroup = group;
group = group.getParent();
}
Thread[] slackList = new Thread[topGroup.activeCount() ];
// 获取根线程组的所有线程
int actualSize = topGroup.enumerate(slackList);
// copy into a list that is the exact size
Thread[] list = new Thread[actualSize];
System.arraycopy(slackList, 0, list, 0, actualSize);
System.out.println("Thread list size == " + list.length);
for (Thread thread : list) {
System.out.println(thread.getName());
}