java_base:线程池

构造一个新的线程所需要的系统资源开销很大。如果在程序中创建了大量的生命周期短的线程,那么需要使用线程池。线程池中有许多准备运行的线程,为线程池提供一个runnable,就会有一个线程调用run方法,当run方法退出时,这个线程不会死亡,而是退还给线程池为下一个请求提供服务

1.使用线程池的好处

降低了资源损耗、提高了响应速度以及线程的可管理性

2.线程池的类型

2.1 定长线程池newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) { 
 
return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); 
 
}

newFixedThreadPool 是一个固定大小的线程池,

2.2 可缓存线程池newCachedThreadPool
public static ExecutorService newCachedThreadPool(){
    return new ThreadPoolExecutor(0,Integer.MAX_VALUE,60L,TimeUnit.MILLISECONDS,new SynchronousQueue<Runnable>());
}

newCachedThreadPool 是一个可以扩大的线程池;比较适合处理时间较小的任务

2.3 单一线程池newSingleThreadExecutor

public static ExecutorService newSingleThreadExecutor(){
    return new ThreadPoolExecutor(1,1,0L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
}

newSingleThreadExecutor只会创建一条工作线程处理任务,采用的阻塞队列为LinkedBlockingQueue;

2.4 可调度的线程池newScheduledThreadPool
 
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE,
          DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
          new DelayedWorkQueue());
}

它用来处理延时任务或定时任务

3.ThreadPoolExecutor

3.1 构造函数
/*
**corePoolSize:该线程池中核心线程数最大值
**int maximumPoolSize: 该线程池中线程总数最大值
**long keepAliveTime:该线程池中非核心线程闲置超时时长
**BlockingQueue workQueue:该线程池中的任务队列:维护着等待执行的Runnable对象
**unit:keepAliveTime的基本时间单位
**threadFactory:线程创建工厂
**handler:拒绝策略处理器
*/
//五个参数的构造函数
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue)
 
//六个参数的构造函数-1
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory)
 
//六个参数的构造函数-2
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          RejectedExecutionHandler handler)
 
//七个参数的构造函数
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler)

3.2 关闭线程池

shutdown() :仅停止阻塞队列中等待的线程,那些正在执行的线程就会让他们执行结束。
shutdownNow() :不仅会停止阻塞队列中的线程,而且会停止正在执行的线程。
关闭时,会遍历所有的线程,调用它们的interrupt函数中断线程。

4.线程池创建方式

1.jdk原生线程池:自己创建ThreadPoolExecutor
2.jdk工具类:Executors工具类
3.spring、tomcat等开源线程池

5.使用

public class Test {
     public static void main(String[] args) {   
         ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 200, TimeUnit.MILLISECONDS,new ArrayBlockingQueue<Runnable>(5));
         for(int i=0;i<15;i++){
         	MyRunnable myRunnable = new MyRunnable(i);
            executor.execute(myRunnable);
            System.out.println("线程数目:"+executor.getPoolSize()+",队列中等待执行的任务数目:"+executor.getQueue().size()+",已执行玩别的任务数目:"+executor.getCompletedTaskCount());
         }
         executor.shutdown();
     }
 }
class MyRunnable implements Runnable {
    private int num;
    public MyRunnable(int num) {
        this.num = num;
    }
    @Override
    public void run() {
        System.out.println("正在执行task "+num);
        try {
            Thread.currentThread().sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("task "+num+"执行完毕");
    }

}

参考

深入浅出java线程池

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值