4:线程池(上)(线程池了解与默认线程池)(文末有项目连接)

1:线程池的作用?
1:降低资源消耗。减少了创建和销毁线程的次数,每个工作线程都可以被重复利用,可执行多个任务。 
2: 提高响应速度。当任务到达时,任务可以不需要的等到线程创建就能立即执行。
3: 提高线程的可管理性。可以根据系统的承受能力,调整线程池中工作线线程的数目,防止因为消耗过多的内存;
2:线程池设计思路
    1: 准备一个任务容器
    2:一次性启动多个(2个)消费者线程
    3: 刚开始任务容器是空的,所以线程都在wait
    4:直到一个外部线程向这个任务容器中扔了一个"任务",就会有一个消费者线程被唤醒
    5: 这个消费者线程取出"任务",并且执行这个任务,执行完毕后,继续等待下一次任务的到来
3;默认线程池
    //1,创建一个默认的线程池对象.池子中默认是空的.默认最多可以容纳int类型的最大值.
    ExecutorService executorService = Executors.newCachedThreadPool();
    //2.参数不是初始值而是最大值
    ExecutorService executorService = Executors.newFixedThreadPool(10);
//两种默认线程池
public class ExecutorsDemo {

    public static void main(String[] args) throws InterruptedException {
        //默认线程池
//        cachedThreadPoolDemo();
        //可以指定线程数量的线程池
//        newFixedThreadPoolDemo();
    }

    private static void cachedThreadPoolDemo() {
        //1,创建一个默认的线程池对象.池子中默认是空的.默认最多可以容纳int类型的最大值.
        ExecutorService executorService = Executors.newCachedThreadPool();
        //Executors --- 可以帮助我们创建线程池对象
        //ExecutorService --- 可以帮助我们控制线程池
        executorService.submit(() -> {
            System.out.println(Thread.currentThread().getName() + "在执行了");
        });
        executorService.submit(() -> {
            System.out.println(Thread.currentThread().getName() + "在执行了");
        });
        executorService.shutdown();
    }

    private static void newFixedThreadPoolDemo() {
        //参数不是初始值而是最大值
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        ThreadPoolExecutor pool = (ThreadPoolExecutor) executorService;
        //大小为0
        System.out.println(pool.getPoolSize());
        executorService.submit(() -> {
            System.out.println(Thread.currentThread().getName() + "在执行了");
        });
        executorService.submit(() -> {
            System.out.println(Thread.currentThread().getName() + "在执行了");
        });
        //大小为2
        System.out.println(pool.getPoolSize());
        executorService.shutdown();
    }
}

项目连接

请配合项目代码食用效果更佳:
项目地址:
https://github.com/hesuijin/hesuijin-study-project
Git下载地址:
https://github.com.cnpmjs.org/hesuijin/hesuijin-study-project.git

import-code-demo项目模块下  thread包
    
可阅读newThreadPool包下代码  
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容