美文网首页
11、多线程之线程池

11、多线程之线程池

作者: 24_yu | 来源:发表于2017-11-11 14:11 被阅读0次

    java 通过Executors工厂类一共可以创建四种类型的线程池,通过Executors.newXXX即可创建。下面就分别都介绍一下把分别为:(缓冲、定长、周期、单例)
    newCachedThreadPool创建一个可缓冲线程池,如果线程池长度(数目)超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
    newFixedThreadPool创建一个定长线程池,可控制线程池最大并发数,超出的线程会在队列中等待。
    newScheduledThreadPool创建一个定长线程池,支持定时及周期性任务执行。
    newSingleThreadExcutor创建一个单线程化的线程池,只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO,LIFO,优先级)执行。

    1、newChedThreadPool

    public static ExecutorService newCachedThreadPool(){
        return new ThreadPoolExecutor(0,Integer.MAX_VALUE,60L,TimeUnit.MILLISECONDS,new SynchronousQueue<Runnable>());
    }
    
    
    image.png

    ● 创建一个可根据需要创建新线程的线程池,无限扩大的线程池,比较适合处理执行时间比较小任务。比如:假设说一开始进来10个任务,启动了10个线程,10个任务结束后,然后又来了5个任务(线程还没被回收),这时候会复用之前的线程,不会新起线程
    ● corePoolSize为0,maximumPoolSize为无限大,意味着线程数量可以无限大;
    ● keepAliveTime为60S,意味着线程空闲时间超过60S就会被杀死;
    ● 采用SynchronousQueue装等待的任务,这个阻塞队列没有存储空间,这意味着只要有请求到来,就必须要找到一条工作线程处理他,如果当前没有空闲的线程,那么就会再创建一条新的线程。

    package com.multithread.learning.Main;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class NewCachedThreadTest {
    
        public static void main(String[] args) {
            
            ExecutorService excutor = Executors.newCachedThreadPool();
            
            for (int i = 0; i < 10; i++) {
                final int index = i;
    
                excutor.execute(new Runnable() {
    
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName()+":"+index);
                    }
                });
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("--------------------");
            for (int i = 0; i< 10; i++){
                final int index = i;
                excutor.execute(new Runnable(){
                    
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName()+":"+index);
                    }
                
                });
            }
            executor.shutdown();
        }
    
    }
    

    执行结果:

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

    由上述结果可以看出,前面执行10次输出,线程池中创建了10个线程,而后面10此输出则是使用前面的线程进行执行。

    2、newFixedThreadPool

    创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

    public static ExecutorService newFixedThreadPool(int nThreads){
    return new ThreadPoolExecutor(nThreads,nThreads,0L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());}
    
    image.png

    ● 是一种固定大小的线程池;
    ● corePoolSize和maxinumPoolSize都为用户设定的线程数量nThreads;
    ● keepAliveTime为0,意味着一旦有空余的空闲线程,就会被立即停止掉;但这里keepAliveTime无效
    ● 阻塞队列采用了LinkedBlockingQueue,是一个无界队列
    ● 由于采用了无界队列,实际线程数量将永远维持在nThreads,因此maximumPoolSize和keepAliveTime将无效。

    package com.multithread.test;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class NewFixedThreadPoolDemo {
        
        
        public static void main(String[] args ){
            
            ExecutorService executor = Executors.newFixedThreadPool(3);
            
            for (int i = 0; i < 10; i++){
                final int index = i;
                
                executor.execute(new Runnable(){
    
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName()+":"+index);
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    
                });
            }
            executor.shutdown();
        }
    }
    
    pool-1-thread-2:1
    pool-1-thread-3:2
    pool-1-thread-1:0
    pool-1-thread-1:3
    pool-1-thread-2:4
    pool-1-thread-3:5
    pool-1-thread-3:7
    pool-1-thread-2:8
    pool-1-thread-1:6
    pool-1-thread-2:9
    

    线程池大小为3,超过数目的线程创建要求则进入等待序列,每个任务输出index后sleep2秒,所以每两秒输出3个数字

    3、newScheduledThread

    创建一个定长线程池,支持定时及周期性任务执行,用来处理延迟任务或者定时任务


    image.png

    延迟执行例子:

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
            
            executor.schedule(new Runnable(){
    
                @Override
                public void run() {
                    System.out.println(" delay 5 seconds");
                }
                
            }, 5, TimeUnit.SECONDS);
            executor.shutdown();
    

    上述代码,表示在延迟5秒后执行输出。

    定期执行例子:

            executor.scheduleAtFixedRate(new Runnable(){
    
                @Override
                public void run() {
                    System.out.println("延迟1秒后,每三秒执行一次");
                }
                
            }, 1,3,TimeUnit.SECONDS);
    

    延迟一秒后每三秒执行一次,不shutdown则一直执行下去

    4、newSingleThreadExecutor

    创建一个单线程的线程池,只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序执行

            ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
            for (int i = 0; i < 10; i++) {
                final int index = i;
                singleThreadExecutor.execute(new Runnable() {
    
                    @Override
                    public void run() {
                        try {
                            System.out.println(Thread.currentThread().getName()+":"+index);
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block e.printStackTrace();
                        }
                    }
                });
            }
            singleThreadExecutor.shutdown();
    
    pool-1-thread-1:0
    pool-1-thread-1:1
    pool-1-thread-1:2
    pool-1-thread-1:3
    pool-1-thread-1:4
    pool-1-thread-1:5
    pool-1-thread-1:6
    pool-1-thread-1:7
    pool-1-thread-1:8
    pool-1-thread-1:9
    

    相关文章

      网友评论

          本文标题:11、多线程之线程池

          本文链接:https://www.haomeiwen.com/subject/qpvimxtx.html