亲宝软件园·资讯

展开

ThreadPool线程池 一篇文章带你了解Java中ThreadPool线程池

Tttori 人气:0
想了解一篇文章带你了解Java中ThreadPool线程池的相关内容吗,Tttori在本文为您仔细讲解ThreadPool线程池的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:ThreadPool线程池,java,ThreadPool,下面大家一起来学习吧。

ThreadPool

线程池的优势

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

线程池的特点

线程复用、控制最大并发数、管理线程


1 线程池的方法

执行长期任务性能好,创建一个线程池,一池有N个固定的线程,可以控制线程最大并发数,有固定线程数的线程池[

ExecutorService threadPool = Executors.newFixedThreadPool(N);

单个任务执行,它只会使用单个工作线程,一池一线程

ExecutorService threadPool = Executors.newSingleThreadExecutor();

执行短期异步任务,可缓存线程池,线程池根据需要创建新线程,但在先前构造的线程可以复用,也可灵活回收空闲的线程,可扩容的池

ExecutorService threadPool = Executors.newCachedThreadPool();

周期性线程池;支持定时及周期性任务执行

ExecutorService threadPool = Executors.newScheduledThreadPool();

(1) newFixedThreadPool

可以控制线程最大并发数的线程池:

public class FixedThreadPool {

    private static AtomicInteger num = new AtomicInteger(0);

    private static ExecutorService executorService = Executors.newFixedThreadPool(2);

    public static void main(String[] args) {
        countSum c= new countSum();
        //将coutSum作为Task,submit至线程池
        for (int i = 0; i < 2; i++) {
            executorService.submit(c);
        }
        //Task执行完成后关闭
        executorService.shutdown();
    }

    static class countSum implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i < 500; i++) {
                try{
                    System.out.println("Thread - "+Thread.currentThread().getName()+" count= "+ num.getAndIncrement());
                    Thread.sleep(100);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}

结果:

(2) newSingleThreadExecutor

只会使用唯一的工作线程执行任务的线程池:

public class SingleThreadExecutor {

    private static AtomicInteger num = new AtomicInteger(0);

    private static ExecutorService executorService = Executors.newSingleThreadExecutor();

    public static void main(String[] args) {
        //将coutSum作为Task,submit至线程池
        for (int i = 0; i < 2; i++) {
            executorService.submit(new countSum());
        }
        //Task执行完成后关闭
        executorService.shutdown();
    }

    static class countSum implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i < 500; i++) {
                try{
                    System.out.println("Thread - "+Thread.currentThread().getName()+" count= "+ num.getAndIncrement());
                    Thread.sleep(100);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}

结果:

(3) newScheduledThreadPool

传参值为corePoolSize大小,支持定时及周期性任务执行

延期执行示例:调用schedule方法,三个参数:Task,Delay,TimeUnit

public class ScheduledThreadPool {
    // corePoolSize = 2
    private static ScheduledExecutorService service = Executors.newScheduledThreadPool(2);

    public static void main(String[] args) {
        System.out.println("Thread - "+Thread.currentThread().getName()+" BEGIN "+ new Date());

        service.schedule(new print(),5, TimeUnit.SECONDS);

        service.shutdown();
    }

    static class print implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try{
                    System.out.println("Thread - "+Thread.currentThread().getName()+" Delay 5 second and sleep 2 second "+ new Date());
                    Thread.sleep(2000);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}

结果:

定时执行示例:调用scheduleAtFixedRate方法,四个参数:Task,initialDelay,Period,TimeUnit

public class ScheduledThreadPool {
    // corePoolSize = 1
    private static ScheduledExecutorService service = Executors.newScheduledThreadPool(1);

    public static void main(String[] args) {

        System.out.println("Thread - "+Thread.currentThread().getName()+" BEGIN "+ new Date());

        service.scheduleAtFixedRate(new print(),5,3,TimeUnit.SECONDS);
    }

    static class print implements Runnable{
        @Override
        public void run() {
            System.out.println("Thread - "+Thread.currentThread().getName()+" Delay 5 second and period 3 second "+ new Date());
        }
    }
}

结果:

(4) newCachedThreadPool

可缓存线程池,如果线程池长度超过处理需要,回收空闲线程,若无可回收,则新建线程。即若前一个任务已完成,则会接着复用该线程:

public class CachedThreadPool {

    private static AtomicInteger num = new AtomicInteger(0);

    private static ExecutorService service = Executors.newCachedThreadPool();

    public static void main(String[] args) {
        countSum c = new countSum();
        for (int i = 0; i < 3; i++) {
            try {
                service.submit(c);
                Thread.sleep(1000);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        service.shutdown();
    }

    static class countSum implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                System.out.println("Thread - "+Thread.currentThread().getName()+" countSum= "+num.getAndIncrement());
            }
        }
    }
}

结果:Thread.sleep(1000)即sleep一秒,上个任务完成可继续复用该线程,不需要创建新的线程

若将Tread.sleep(1000)注释掉,你会发现有3个线程在跑

若感兴趣可以去了解一下它们的底层源码,对于CachedThreadPool而言,可新建线程最大数量为INTEGER.MAXIMUM

2 线程池底层原理

以newFixedThreadPool为例

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>());
}
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,Executors.defaultThreadFactory(), defaultHandler);
    }

线程池七大参数

线程池四大流程

1)创建线程池后,开始等待请求

2)当调用execute()方法添加一个请求任务时,线程池会做以下判断:

3)当一个线程完成任务时,会从等待队列中取下一个任务来执行

4)当空闲线程超过keepAliveTime定义时间,会判断:


3 线程池策略及分析

Note:阿里巴巴JAVA开发手册:线程池不允许使用Executors去创建线程池,而是通过使用ThreadPoolExecutor的方式自定义线程池,规避资源耗尽的风险

Executors返回的线程池对象的弊端:

1)FixedThreadPool和SingleThreadPool:

​允许请求队列长度为Integer.MAX_VALUE,可能会堆积大量请求导致OOM

2)CachedThreadPool和ScheduledThreadPool:

​允许创建线程数量为Integer.MAX_VALUE,可能会创建大量的线程导致OOM


拒绝策略

1)AbortPolicy

​直接抛出RejectedExecutionException异常阻止系统正常运行

2)CallerRunsPolicy

​"调用者运行"的调节机制,该策略既不会抛弃任务,也不会抛出异常,而是将某些任务回退到调用者,从而降低新任务的流量

3)DiscardPolicy

​该策略抛弃无法处理的任务,不予任何处理也不抛出异常。如果允许任务丢失,这是最好的一种策略

4)DiscardOldestPolicy

​抛弃队列中等待最久的任务,然后把当前任务加入队列中尝试再次提交当前任务


如何设置maximumPoolSize大小

Runtime.getRuntime().availableProcessors()方法获取核数

CPU密集型

​maximumPoolSize设为核数+1

IO密集型

​maximumPoolSize设为核数/阻塞系数

加载全部内容

相关教程
猜你喜欢
用户评论