线程池的设计

线程池

每一个线程的启动和结束都是比较消耗时间和占用资源的。
如果在系统中用到了很多的线程,大量的启动和结束动作会导致系统的性能变卡,响应变慢。
为了解决这个问题,引入线程池这种设计思想。
线程池的模式很像生产者消费者模式,消费的对象是一个一个的能够运行的任务

设计思路

线程池的思路和生产者消费者模型是很接近的。

  1. 准备一个任务容器
  2. 一次性启动10个 消费者线程
  3. 刚开始任务容器是空的,所以线程都wait在上面。
  4. 直到一个外部线程往这个任务容器中扔了一个“任务”,就会有一个消费者线程被唤醒notify
  5. 这个消费者线程取出“任务”,并且执行这个任务,执行完毕后,继续等待下一次任务的到来。
  6. 如果短时间内,有较多的任务加入,那么就会有多个线程被唤醒,去执行这些任务。

开发并测试线程池

package multiThread3;

import java.util.LinkedList;

public class ThreadPool {
//    define the tasks in the threads of pool
    LinkedList<Runnable> tasks = new LinkedList<>();
//    define the size of threads of pool
    int threadPoolSize;
//    the thread of trying to consume
    public ThreadPool(){
        threadPoolSize = 10;
//        start the threads of pool
        synchronized (tasks){
            for (int i = 0; i < threadPoolSize; i++) {
                new TaskConsumeThread("任务消费者线程"+i).start();
            }
        }
    }
    public void add(Runnable r){
        synchronized (tasks){
            tasks.add(r);
//            After adding the object of Runnable, calling the objects of all the objects.
            tasks.notifyAll();
        }
    }

    class TaskConsumeThread extends Thread{
        public TaskConsumeThread(String name){
            super(name);
        }
        Runnable task;

        @Override
        public void run() {
            System.out.println("启动"+this.getName());
            while (true){
                synchronized (tasks){
                    while (tasks.isEmpty()){
                        try{
                            tasks.wait();
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                    }
                    task=tasks.removeLast();
                    tasks.notifyAll();
                }
                System.out.println(this.getName()+"获取任务,立刻执行");
                task.run();
            }
        }
    }
}

package multiThread3;

public class test {
    public static void main(String[] args) {
        ThreadPool threadPool = new ThreadPool();
        int sleep =1000;
        for (int i = 0; i < 10; i++) {
            Runnable task = () -> {
                try{
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            };
            threadPool.add(task);
            try {
                Thread.sleep(sleep);
                sleep=sleep>100?sleep-100:sleep;
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

在这里插入图片描述

使用java自带线程池

java有提供自带的线程池ThreadPoolExecutor
第一个参数10 表示这个线程池初始化了10个线程在里面工作
第二个参数15 表示如果10个线程不够用了,就会自动增加到最多15个线程
第三个参数60 结合第四个参数TimeUnit.SECONDS,表示经过60秒,多出来的线程还没有接到活儿,就会回收,最后保持池子里就10个
第四个参数TimeUnit.SECONDS 如上
第五个参数 new LinkedBlockingQueue() 用来放任务的集合

package multiThread4;

import java.util.concurrent.*;

public class test {
    public static void main(String[] args) {

//        public ThreadPoolExecutor(int corePoolSize,
//        int maximumPoolSize,
//        long keepAliveTime,
//        TimeUnit unit,
//        BlockingQueue<Runnable> workQueue) {
//            this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
//                    Executors.defaultThreadFactory(), defaultHandler);
//        }
        ThreadPoolExecutor thread =
                new ThreadPoolExecutor(10,
                        15,
                        60,
                        TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());
//        add new thread
        thread.execute(() -> {
            System.out.println("任务1");
        });
    }
}
  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值