自定義線程池中線程
1.ThreadFactory
主要方法是 newThread
為每個線程設(shè)置名字和屬于的線程組
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中自帶的實現(xiàn)的線程池都是根據(jù)此生成的
/**
*
* @param corePoolSize 核心線程池大小
* @param maximumPoolSize 線程池最大容量
* @param keepAliveTime 線程池空閑時,線程存活的時間
* @param unit 單位
* @param workQueue 工作隊列
* @param threadFactory 線程工廠
* @param handler 處理當(dāng)線程隊列滿了鲜结,也就是執(zhí)行拒絕策略
*/
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