自定义ThreadFactory和ThreadGroup

自定义线程池中线程

优秀博文

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 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

你可能感兴趣的:(自定义ThreadFactory和ThreadGroup)