多线程(1) : 线程池项目应用

作为类的一个属性存在

    private ExecutorService executorService = new ThreadPoolExecutor(5, 10,
            3000, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(10));

源码

public ThreadPoolExecutor(int corePoolSize, //初始线程数
                              int maximumPoolSize,//最大线程数
                              long keepAliveTime,//持续时间
                              TimeUnit unit,//时间单位
                              BlockingQueue workQueue) {//多的线程进入队列
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }

 使用

 executorService.submit(new Runnable() {
                @Override
                public void run() {
                    // 要执行的代码/方法
                }
            });

 

推荐使用带 ThreadFactory 参数的,方便设置线程名字

    private ExecutorService executorService = new ThreadPoolExecutor(5, 10,
            3000, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(10),new ThreadFactoryBuilder()
            .setNameFormat("demo-pool-%d").build());

 

ThreadFactoryBuilder 包全路径与maven坐标

import com.google.common.util.concurrent.ThreadFactoryBuilder;

    com.google.guava
    guava
    18.0

 

创建线程或线程池时请指定有意义的线程名称,方便出错时回溯。
创建线程池的时候请使用带ThreadFactory的构造函数,并且提供自定义ThreadFactory实现或者使用第三方实现。
public class TimerTaskThread extends Thread {
    public TimerTaskThread(){
    super.setName("TimerTaskThread");
    // ...
}
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
    .setNameFormat("demo-pool-%d").build();
ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1,
    0L, TimeUnit.MILLISECONDS,
    new LinkedBlockingQueue(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

singleThreadPool.execute(()-> System.out.println(Thread.currentThread().getName()));
singleThreadPool.shutdown();

 

 参考 : https://www.cnblogs.com/sharoncmt/p/7511126.html

 

END

你可能感兴趣的:(多线程)