【多线程】ThreadPool线程池

一、背景(为什么使用线程池)

线程池的优势:

线程池做的工作主要是控制运行的线程的数量,处理过程中将任务放入队列,然后在线程创建后启动这些任务,如果线程数量超过了最大数量超出数量的线程排队等候,等其他线程执行完毕,再从队列中取出任务来执行。

线程池的特点:线程复用,控制最大并发数,管理线程

一、降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的小号。

二、提高响应速度。当任务到达时,任务可以不需要等待线程创建就能立即执行。

三、提高线程的可管理性。线程是稀缺资源,如果无限制创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控。

二、线程池的使用

1.架构说明

Java中的线程池是通过Executor框架实现的,该框架中用到了Executor,Executors,ExecutorService,ThreadPoolExecutor这几个类。Executors相当月Executor得工具类。(类比Arrays)

2.编码实现

(1)Executors.newFixedThreadPool(int):执行长期任务性能好,创建一个线程池,一池有N个固定的线程,有固定线程数的线程

public class MyThreadPoolDemo {

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);//一个池5个受理线程,类比5个窗口

        try{
            //模拟有10个顾客办理业务
            for (int i = 1; i <= 10; i++){
                threadPool.execute(() -> System.out.println(Thread.currentThread().getName()+"\t 办理业务"));
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }
}

 (2)Executors.newSingleThreadExecutor()一个任务一个任务的执行,一池一线程

public class MyThreadPoolDemo {

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();//一个池1个受理线程,类比1个窗口

        try{
            //模拟有10个顾客办理业务
            for (int i = 1; i <= 10; i++){
                threadPool.execute(() -> System.out.println(Thread.currentThread().getName()+"\t 办理业务"));
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }
}

(3)Executors.newCachedThreadPool()执行很多短期异步任务,线程池根据需要创建新线程,但在先前构建的线程可用时将重用它们。可扩容,遇强则强

public class MyThreadPoolDemo {

    public static void main(String[] args) {
//        ExecutorService threadPool = Executors.newFixedThreadPool(5);//一个池5个受理线程,类比5个窗口
//        ExecutorService threadPool = Executors.newSingleThreadExecutor();//一个池1个受理线程,类比1个窗口
        ExecutorService threadPool = Executors.newCachedThreadPool();//一池N个工作线程,类似N个窗口
        try{
            //模拟有10个顾客办理业务
            for (int i = 1; i <= 10; i++){
//              延迟,避免执行太快导致创建线程过多
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e){
                    e.printStackTrace();
                }
                threadPool.execute(() -> System.out.println(Thread.currentThread().getName()+"\t 办理业务"));
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }
}
发布了103 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/zzf_forgot/article/details/103197627