线程池的使用

本文通过对比分析无线程池和使用线程池的示例,展示了线程池如何有效管理和复用线程,避免资源浪费。线程池允许预先创建一定数量的线程,当任务提交时,线程池会分配空闲线程执行,提高系统效率并减少创建和销毁线程的开销。在Java中,`ExecutorService`和`Executors`类提供了线程池的实现。
摘要由CSDN通过智能技术生成

线程和数据库连接这些资源都是非常宝贵的资源。那么每次需要的时候创建,不需要的时候销毁,是非常浪费资源的。那么我们就可以使用缓存的策略,也就是使用线程池。

public class ThreadPoolTest {
    //1、不用线程池
    //函数式接口实现,重写run
    public static void noPool(){

        Runnable target=()->{
            for (int i=0;i<10;i++){
                System.out.println(Thread.currentThread().getName()+":"+i);
            }
        };
        //手动创建两个线程并启动
        //传入一个Runnable实例作为target
        new Thread(target).start();
        new Thread(target).start();


    }
    //2、使用线程池
    public static void usePool(){
        //不需要自己创建线程,只需要创建线程池,将target(要执行的任务)提交给线程池,线程池就会分配两个空闲的线程来执行
        ExecutorService pool= Executors.newFixedThreadPool(6);
        Runnable target=()->{
            for (int i=0;i<10;i++){
                System.out.println(Thread.currentThread().getName()+":"+i);
            }
        };
        //向线程池提交两个线程
        pool.submit(target);
        pool.submit(target);
        //关闭线程池
        pool.shutdown();
    }
    public static void main(String[] args) {
        noPool();
        usePool();
    }
}


Thread-1:0
Thread-1:1
Thread-1:2
Thread-0:0
Thread-1:3
Thread-0:1
Thread-1:4
Thread-0:2
Thread-1:5
Thread-0:3
Thread-1:6
Thread-1:7
Thread-0:4
Thread-0:5
Thread-0:6
Thread-1:8
Thread-0:7
Thread-0:8
Thread-1:9
Thread-0:9
pool-1-thread-2:0
pool-1-thread-1:0
pool-1-thread-2:1
pool-1-thread-1:1
pool-1-thread-2:2
pool-1-thread-1:2
pool-1-thread-2:3
pool-1-thread-1:3
pool-1-thread-2:4
pool-1-thread-1:4
pool-1-thread-2:5
pool-1-thread-1:5
pool-1-thread-2:6
pool-1-thread-1:6
pool-1-thread-2:7
pool-1-thread-1:7
pool-1-thread-2:8
pool-1-thread-1:8
pool-1-thread-2:9
pool-1-thread-1:9


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值