阻塞队列和线程池

写入:如果队列满了,就必须阻塞等待

取出:如果队列是空的,必须阻塞等待生产

阻塞队列:

阻塞队列和线程池

 

 ArrayBlockingQueue(数组的阻塞队列)、 LinkedBlockingQueue(链表的阻塞队列),SynchronousQueue(同步队列)

SynchronousQueue(同步队列):一种阻塞队列,其中每个插入操作必须等待另一个线程的对应移除操作 ,反之亦然。同步队列没有任何内部容量,甚至连一个队列的容量都没有。

 

线程池

好处:降低资源消耗、提高响应速度、方便管理线程;也就是线程复用、控制最大并发数、管理线程

创建线程池的三大方法:

package com.pool;

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

//使用了线程池后,使用线程池创建线程
public class demo1 {
    public static void main(String[] args) {
        //Executors.newSingleThreadExecutor();//单个线程的池
        //Executors.newFixedThreadPool(5);//创建一个固定的线程池
        ExecutorService threadPool = Executors.newCachedThreadPool();//创建一个可伸缩的线程池

        try {
            for (int i = 0; i <10 ; i++) {
                //用线程池来创建线程
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"ok");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }
}

七大参数:

点进newCachedThreadPool()源码里面,可以看到七个方法

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;
    }

四大拒绝策略:

  • rejected = new ThreadPoolExecutor.AbortPolicy();//默认,队列满了丢任务抛出异常
  • rejected = new ThreadPoolExecutor.DiscardPolicy();//队列满了丢弃任务,不抛出异常
  • rejected = new ThreadPoolExecutor.DiscardOldestPolicy();//将最早进入队列的任务删,之后再尝试加入队列
  • rejected = new ThreadPoolExecutor.CallerRunsPolicy();// 将处理不了的任务返回给调用者

 

上一篇:线程池——ThreadPoolExecutor


下一篇:线程池-ThreadPoolExecutor