自定义ThreadFactory和ThreadGroup
【摘要】
自定义线程池中线程
优秀博文
1.ThreadFactory
主要方法是 newThread 为每个线程设置名字和属于的线程组
public class NamedThreadFactory implements ThreadFactory { /** *原子操作保证每个线程都有唯一的 */ pri...
自定义线程池中线程
1.ThreadFactory
主要方法是 newThread
为每个线程设置名字和属于的线程组
-
public class NamedThreadFactory implements ThreadFactory {
-
-
/**
-
*原子操作保证每个线程都有唯一的
-
*/
-
private static final AtomicInteger threadNumber=new AtomicInteger(1);
-
-
private final AtomicInteger mThreadNum = new AtomicInteger(1);
-
-
private final String prefix;
-
-
private final boolean daemoThread;
-
-
private final ThreadGroup threadGroup;
-
-
public NamedThreadFactory() {
-
this("rpcserver-threadpool-" + threadNumber.getAndIncrement(), false);
-
}
-
-
public NamedThreadFactory(String prefix) {
-
this(prefix, false);
-
}
-
-
-
public NamedThreadFactory(String prefix, boolean daemo) {
-
this.prefix = StringUtils.isNotEmpty(prefix) ? prefix + "-thread-" : "";
-
daemoThread = daemo;
-
SecurityManager s = System.getSecurityManager();
-
threadGroup = (s == null) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup();
-
}
-
-
@Override
-
public Thread newThread(Runnable runnable) {
-
String name = prefix + mThreadNum.getAndIncrement();
-
Thread ret = new Thread(threadGroup, runnable, name, 0);
-
ret.setDaemon(daemoThread);
-
return ret;
-
}
-
}
2. ThreadPoolExecutor
JDK中自带的实现的线程池都是根据此生成的
-
/**
-
*
-
* @param corePoolSize 核心线程池大小
-
* @param maximumPoolSize 线程池最大容量
-
* @param keepAliveTime 线程池空闲时,线程存活的时间
-
* @param unit 单位
-
* @param workQueue 工作队列
-
* @param threadFactory 线程工厂
-
* @param handler 处理当线程队列满了,也就是执行拒绝策略
-
*/
-
public ThreadPoolExecutor(int corePoolSize,
-
int maximumPoolSize,
-
long keepAliveTime,
-
TimeUnit unit,
-
BlockingQueue<Runnable> workQueue,
-
ThreadFactory threadFactory,
-
RejectedExecutionHandler handler){}
-
自定义异常
-
@Override
-
public void run() {
-
System.out.println(Thread.currentThread().getName());
-
if ("RpcThreadPool-thread-10".equalsIgnoreCase(Thread.currentThread().getName())){
-
try{
-
int s=1/0;
-
}catch (Exception e){
-
Thread.currentThread().getThreadGroup().uncaughtException(Thread.currentThread(),new Exception("自定义",e));
-
}
-
-
}
-
}
-
-
RpcThreadPool-thread-22
-
Exception in thread "RpcThreadPool-thread-10" java.lang.Exception: 自定义
-
at rpc.core.threads.Task.run(Task.java:19)
-
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
-
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
-
at java.lang.Thread.run(Thread.java:745)
-
Caused by: java.lang.ArithmeticException: / by zero
-
at rpc.core.threads.Task.run(Task.java:17)
-
... 3 more
-
RpcThreadPool-thread-23
-
RpcThreadPool-thread-24
-
文章来源: springlearn.blog.csdn.net,作者:西魏陶渊明,版权归原作者所有,如需转载,请联系作者。
原文链接:springlearn.blog.csdn.net/article/details/102425327
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)