欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JUC之线程池

程序员文章站 2022-07-13 14:42:53
...

JUC之线程池

package juc.day03;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolTest {
    public static void main(String[] args) {
        //Executor --->   ExecutorService
        //一个线程里创建8个工作线程
        ExecutorService service = Executors.newFixedThreadPool(2);
        try{
            for (int i = 1; i <= 4 ; i++) {
                service.execute(()->{
                    System.out.println("银行工作人员--"+Thread.currentThread().getName()+"--\t 提供服务");
                });
            }
        }finally {
            service.shutdown();
        }


    }
}

  ExecutorService service = Executors.newSingleThreadExecutor();//只有一个线程
  ExecutorService service1 = Executors.newCachedThreadPool();//N个线程,自动扩容

源码

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

这三个底层都是new ThreadPoolExecutor();
用到了阻塞队列
有七个参数

public ThreadPoolExecutor(int corePoolSize,//常驻线程数
                              int maximumPoolSize,//最大线程数
                              long keepAliveTime,//线程存活时间
                              TimeUnit unit,//存活时间单位
                              BlockingQueue<Runnable> workQueue,//候客区,等候区
                              ThreadFactory threadFactory,//线程创建工厂
                              RejectedExecutionHandler handler//拒绝策略,表示候客区满了后的策略) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

JUC之线程池

线程池底层工作原理(参考银行服务窗口,等候区)

这三个用哪一个,都不用,使用自定义的线程池
JUC之线程池

JUC之线程池

处理的任务数,为最大线程数+队列长度,如果超过这个长度,策略将会执行

拒绝策略
1.AbortPolicy ----> 报异常(中断策略)
2.CallerRunsPolicy----->将任务回退到调用者,不会抛异常 --------实际测试结果返回给了main线程
3.DiscardOldestPolicy------>等待时间最长的任务,直接抛弃
4.DiscardPolicy------->抛弃策略,超过了处理数,直接丢弃