java线程池的使用

java自带的线程池

  • 可缓存线程池

    特点:对线程的个数没有限制,无法控制线程的最大并发数
    使用:

    ExecutorService executorService = Executors.newCachedThreadPool()
    executorService .execute(Runnable MyRunnable)
    
  • 定长线程池

    特点:指定最大线程的个数
    使用:

    ExecutorService executorService = Executors.newFixedThreadPool(10)
    executorService .execute(Runnable MyRunnable)
    
  • 单线程线程池

    特点:先来的先执行,有顺序
    使用:

    ExecutorService executorService = Executors.newSingleThreadExecutor()
    executorService .execute(Runnable MyRunnable)
    
  • 计划任务线程池

    特点:可以做定时任务
    使用:

    ExecutorService executorService = Executors.newScheduledThreadPool(10)
    schedule(Runnable MyRunnable,	//自定义Runnable
             long delay,	//时间数值,例:5
             TimeUnit unit)	//时间单位,例:TimeUnit.SECONDS(秒)
    

自定义线程池

ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
											int corePoolSize,	//核心线程数,初始化线程数量
                              				int maximumPoolSize,	//最大线程数量
                             				long keepAliveTime,	//线程等待任务的最大空闲时间
                              				TimeUnit unit,		//时间单位
                              				BlockingQueue<Runnable> workQueue,//阻塞队列,存放还没有执行的线程任务
											ThreadFactory threadFactory,	//创建线程工厂,默认工厂:Executors.defaultThreadFactory()
                              				RejectedExecutionHandler handler//拒绝策略(丢弃任务抛异常,丢弃任务不抛异常,丢弃队列最前面的任务,有点用线程处理盖该任务),默认:defaultHandler
                              				)

例:

ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5,
        10,
        60,
        TimeUnit.SECONDS,
        new LinkedBlockingQueue<>(50),
        Executors.defaultThreadFactory(),
        new ThreadPoolExecutor.AbortPolicy());

threadPoolExecutor.execute(new Runnable() {
    @Override
    public void run() {
        System.out.println("我是 Runnable. ");
    }
});
Future<String> future = threadPoolExecutor.submit(new Callable<String>() {
    @Override
    public String call() throws Exception {
        System.out.println("我是 Callable. ");
        return "Callable";
    }
});
Object str = future.get();
//Object str = future.get(10,//最大等待时间
//          TimeUnit.SECONDS);//时间单位
System.out.println(str);
posted @   叕叕666  阅读(35)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示