Java-五种线程池,四种拒绝策略,三类阻塞队列

Java-五种线程池,四种拒绝策略,三类阻塞队列(常用)

三类阻塞队列:
    //1 有界队列
    workQueue = new ArrayBlockingQueue<>(5);//基于数组的先进先出(FIFO)队列,支持公平锁和非公平锁,有界
    workQueue = new LinkedBlockingQueue<>();//基于链表的先进先出(FIFO)队列,默认长度为 Integer.MaxValue 有OOM危险,有界
    workQueue = new LinkedBlockingDeque(); //一个由链表结构组成的,双向阻塞队列,有界
    //2 无界队列
    workQueue = new PriorityBlockingQueue(); //支持优先级排序的无限队列,默认自然排序,可以实现 compareTo()方法指定排序规则,不能保证同优先级元素的顺序,无界。
    workQueue = new DelayQueue(); //一个使用优先级队列(PriorityQueue)实现的无界延时队列,在创建时可以指定多久才能从队列中获取当前元素。只有延时期满后才能从队列中获取元素。
    workQueue = new LinkedTransferQueue(); //一个由链表结构组成的,无界阻塞队列
    //3 同步移交队列
    workQueue = new SynchronousQueue<>();//无缓冲的等待队列,队列不存元素,每个put操作必须等待take操作,否则无法添加元素,支持公平非公平锁,无界

java.util.concurrent 包下的阻塞队列及其依赖关系

 

四种拒绝策略:
    RejectedExecutionHandler rejected = null;
    rejected = new ThreadPoolExecutor.AbortPolicy();//默认,队列满了丢任务抛出异常
    rejected = new ThreadPoolExecutor.DiscardPolicy();//队列满了丢任务不异常
    rejected = new ThreadPoolExecutor.DiscardOldestPolicy();//将最早进入队列的任务删,之后再尝试加入队列
    rejected = new ThreadPoolExecutor.CallerRunsPolicy();//如果添加到线程池失败,那么主线程会自己去执行该任务

五种线程池:
    ExecutorService threadPool = null;
    threadPool = Executors.newCachedThreadPool();//有缓冲的线程池,线程数 JVM 控制
    threadPool = Executors.newFixedThreadPool(3);//固定大小的线程池
    threadPool = Executors.newScheduledThreadPool(2);
    threadPool = Executors.newSingleThreadExecutor();//单线程的线程池,只有一个线程在工作
    threadPool = new ThreadPoolExecutor();//默认线程池,可控制参数比较多   

public static void main (String[] args) throws Exception {
    testThreadPoolExecutor();
}
public static void testThreadPoolExecutor() throws Exception {
    //基础参数
    int corePoolSize=2;//最小活跃线程数
    int maximumPoolSize=5;//最大活跃线程数
    int keepAliveTime=5;//指定线程池中线程空闲超过 5s 后将被回收
    TimeUnit unit = TimeUnit.SECONDS;//keepAliveTime 单位
    //阻塞队列
    BlockingQueue<Runnable> workQueue = null;
	//1 有界队列
	workQueue = new ArrayBlockingQueue<>(5);//基于数组的先进先出(FIFO)队列,支持公平锁和非公平锁,有界
	workQueue = new LinkedBlockingQueue<>();//基于链表的先进先出(FIFO)队列,默认长度为 Integer.MaxValue 有OOM危险,有界
	workQueue = new LinkedBlockingDeque(); //一个由链表结构组成的,双向阻塞队列,有界
	//2 无界队列
	workQueue = new PriorityBlockingQueue(); //支持优先级排序的无限队列,默认自然排序,可以实现 compareTo()方法指定排序规则,不能保证同优先级元素的顺序,无界。
	workQueue = new DelayQueue(); //一个使用优先级队列(PriorityQueue)实现的无界延时队列,在创建时可以指定多久才能从队列中获取当前元素。只有延时期满后才能从队列中获取元素。
	workQueue = new LinkedTransferQueue(); //一个由链表结构组成的,无界阻塞队列
	//3 同步移交队列
	workQueue = new SynchronousQueue<>();//无缓冲的等待队列,队列不存元素,每个put操作必须等待take操作,否则无法添加元素,支持公平非公平锁,无界


    //拒绝策略
    RejectedExecutionHandler rejected = null;
    rejected = new ThreadPoolExecutor.AbortPolicy();//默认,队列满了丢任务抛出异常
    rejected = new ThreadPoolExecutor.DiscardPolicy();//队列满了丢任务不异常
    rejected = new ThreadPoolExecutor.DiscardOldestPolicy();//将最早进入队列的任务删,之后再尝试加入队列
    rejected = new ThreadPoolExecutor.CallerRunsPolicy();//如果添加到线程池失败,那么主线程会自己去执行该任务


    //使用的线程池
    ExecutorService threadPool = null;
    threadPool = Executors.newCachedThreadPool();//有缓冲的线程池,线程数 JVM 控制
    threadPool = Executors.newFixedThreadPool(3);//固定大小的线程池
    threadPool = Executors.newScheduledThreadPool(2);
    threadPool = Executors.newSingleThreadExecutor();//单线程的线程池,只有一个线程在工作
    threadPool = new ThreadPoolExecutor(
            corePoolSize,
            maximumPoolSize,
            keepAliveTime,
            unit,
            workQueue,
            rejected);//默认线程池,可控制参数比较多
    //执行无返回值线程
    TaskRunnable taskRunnable = new TaskRunnable();
    threadPool.execute(taskRunnable);
    List<Future<String>> futres = new ArrayList<>();
    for(int i=0;i<10;i++) {
        //执行有返回值线程
        TaskCallable taskCallable = new TaskCallable(i);
        Future<String> future = threadPool.submit(taskCallable);
        futres.add(future);
    }
    for(int i=0;i<futres.size();i++){
        String result = futres.get(i).get();
        System.out.println(i+" result = "+result);
    }
}
/**
    * 返回值的线程,使用 threadpool.execut() 执行
    */
public static class TaskRunnable implements Runnable{
    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " runnable result!");
    }
}
/**
    * 有返回值的线程,使用 threadpool.submit() 执行
    */
public static class TaskCallable implements Callable<String>{
    public TaskCallable(int index){
        this.i=index;
    }
    private int i;
    @Override
    public String call() throws Exception {
        int r = new Random().nextInt(5);
        try {
            Thread.sleep(r);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //System.out.println("callable result!");
        return Thread.currentThread().getName()+" callable index="+i +",sleep="+r;
    }
}

  • 21
    点赞
  • 151
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
线程池四种拒绝策略分别是: 1. AbortPolicy(中止策略):当线程池无法接受新任务时,会抛出一个拒绝执行的异常信息(RejectedExecutionException),中止任务的执行,并需要处理该异常。这是线程池的默认拒绝策略。 2. CallerRunsPolicy(调用者运行策略):当线程池无法接受新任务时,会使用调用线程直接执行任务。适用于并发较小、性能要求不高的场景,不允许任务失败。然而,如果任务提交速度过快,可能会导致程序阻塞,造成性能上的损失。 3. DiscardPolicy(直接丢弃策略):当线程池无法接受新任务时,直接丢弃当前任务,没有任何提示信息或处理。适用于对任务丢失无关紧要的场景,但需要注意任务的丢失可能会带来潜在的问题。 4. DiscardOldestPolicy(丢弃最老任务策略):当线程池无法接受新任务时,丢弃阻塞队列中最老的一个任务,并将新任务加入队列。适用于对任务响应时间要求较高的场景,丢弃最老任务可以腾出空间来执行新任务。 根据具体的业务场景和需求,可以选择合适的拒绝策略来处理无法接受新任务的情况。一般情况下,使用线程池时,默认采用的是AbortPolicy中止策略。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [线程池-四种拒绝策略总结](https://blog.csdn.net/alan_liuyue/article/details/120995601)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [Java线程池四种拒绝策略](https://blog.csdn.net/a904364908/article/details/107489854)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值