关于Java并发编程中如何自定义线程池

ThreadPoolExecutor:线程池的创建方式有许多种,如FixedThreadPool、CachedThreadPool、ScheduledThreadPool 、SingleThreadPool、ForkJoinPool,但是在实际开发过程中往往都是使用自定线程池。

关于Java并发编程中如何自定义线程池_第1张图片

public class Test_19 {
    /** 即使空闲时仍保留在池中的线程数,除非设置 allowCoreThreadTimeOut*/
    static int corePoolSize = 10;

    /** 池中允许的最大线程数*/
    static int maximumPoolSize  = 100;

    /**当线程数大于核心时,这是多余的空闲线程在终止之前等待新任务的最大时间*/
    static long keepAliveTime = 1;

    /**在执行任务之前用于保存任务的队列, 该队列将仅保存execute方法提交的Runnable任务*/
    static ArrayBlockingQueue workQueue = new ArrayBlockingQueue(10);
    
    /**指定有意义的线程池名称*/
    static MyFactory myFactory = new MyFactory("某线程组");

    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                workQueue,myFactory);
        System.out.println(executor);
        for (int i = 0 ;i<5;i++){
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        TimeUnit.MICROSECONDS.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+" - test executor - ");
                }
            });
        }
        System.out.println(executor);
        executor.shutdown();
        executor.isShutdown();
        executor.isTerminated();
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(executor);
    }
}
/**
* 创建线程或线程池时请指定有意义的线程名称,方便出错时回溯。
* */
class MyFactory implements ThreadFactory{
    private final String namePrefix;
    private AtomicInteger nextId = new AtomicInteger(1);
    MyFactory(String whatFeatureOfGroup){
        this.namePrefix = "From TestFactory's " + whatFeatureOfGroup + " - worker - ";
    }
    @Override
    public Thread newThread(Runnable task) {
        String name = this.namePrefix + nextId.getAndIncrement();
        Thread thread=new Thread(null, task, name, 0);
        System.out.println(thread.getName());
        return thread;
    }
}

阅读原文

你可能感兴趣的:(Java并发编程)