Java-五种线程池,四种拒绝策略,三种阻塞队列
三种阻塞队列
BlockingQueue<Runnable> workQueue = null;
workQueue = new ArrayBlockingQueue<>(5);//基于数组的先进先出队列,有界
workQueue = new LinkedBlockingQueue<>();//基于链表的先进先出队列,无界
workQueue = new SynchronousQueue<>();//无缓冲的等待队列,无界
四种拒绝策略
RejectedExecutionHandler rejected = null;
rejected = new ThreadPoolExecutor.AbortPolicy();//默认,队列满了丢任务抛出异常
rejected = new ThreadPoolExecutor.DiscardPolicy();//队列满了丢任务不异常
rejected = new ThreadPoolExecutor.DiscardOldestPolicy();//将最早进入队列的任务删,之后再尝试加入队列
rejected = new ThreadPoolExecutor.CallerRunsPolicy();//如果添加到线程池失败,那么主线程会自己去执行该任务
如何创建线程池?
直接使用ThreadPoolExecutor类的构造方法就可以创建线程池。我们来看下构造参数:
/**
* corePoolSize 核心线程数
* maximumPoolSize 最大线程数
* keepAliveTime idle线程存活时间
* unit 上个参数的单位
* workQueue 线程对象的缓冲队列
* threadFactory 生成线程的工厂(可选
* handler 达到容量后的回调(可选)
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
五种线程池
ExecutorService threadPool = null;
threadPool = Executors.newSingleThreadExecutor();//单线程的线程池,只有一个线程在工作,阻塞队列使用的是LinkedBlockingQueue
threadPool = Executors.newFixedThreadPool(3);//固定大小的线程池,阻塞队列使用的是LinkedBlockingQueue
threadPool = Executors.newCachedThreadPool();//有缓冲的线程池,线程数 JVM 控制,阻塞队列使用的是SynchronousQueue
threadPool = Executors.newScheduledThreadPool(2);//定时任务功能的线程池
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;
workQueue = new ArrayBlockingQueue<>(5);//基于数组的先进先出队列,有界
workQueue = new LinkedBlockingQueue<>();//基于链表的先进先出队列,无界
workQueue = new SynchronousQueue<>();//无缓冲的等待队列,无界
//拒绝策略
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;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY