java 线程池的使用


1.线程池的概念


线程池:创建线程的生命周期包括创建、就绪,阻塞和销毁阶段,当我们要执行的任务比较小且频繁时,会导致重复的创建线程,避免资源的消耗。线程池中存放我们需要数量的           线程,使用已经创建好的线程去执行我们的操作,避免频繁的创建。


Java通过Executors提供四种线程池,分别为:
      newCachedThreadPool:创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。



2.为什要使用线程池?


    1.单个的任务之多,可以使多个任务有序的执行


       2.处理任务比较频繁,避免重复的创建和销毁线程,减少cpu和资源的使用


3.几种线程池具体的使用方法


newCachedThreadPool:可缓存的线程池的使用


ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        for(int i = 1;i<=5;i++){
            try {
                Thread.sleep(i*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            final int finalI = i;
            cachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("当前执行的 idx=" + finalI);
                }
            });
            int threadCount = ((ThreadPoolExecutor)cachedThreadPool).getActiveCount();//这边有事获取的是1有时是0
            System.out.println("当前活动的线程数 for=" + threadCount);
            int poolCount = ((ThreadPoolExecutor)cachedThreadPool).getPoolSize();
            System.out.println("当前池线程数 for=" + poolCount); //这边使用了缓存的线程,获取到的线程数一直视1
        }
        int threadCount = ((ThreadPoolExecutor)cachedThreadPool).getActiveCount();
        System.out.println("当前活动的线程数=" + threadCount);
        int poolCount = ((ThreadPoolExecutor)cachedThreadPool).getPoolSize();
        System.out.println("当前池线程数=" + poolCount);


getActiveCount:获取当前的线程池的活动的线程数 getPoolSize:获取当前的线程池的线程数



newFixedThreadPool:定长的线程池,超过消息队列会继续等待


ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);
        for(int i = 1;i<=5;i++){
            final int finalI = i;
            if (!fixedThreadPool.isShutdown()) {
                fixedThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("当前执行的 idx=" + finalI);
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
            //不要显示调用shutdown方法,可能会导致RejectedExecutionException,或者判断是否fixedThreadPool.isShutdown(),
            // 如果已经shutdown就不要调用excute方法了
//            fixedThreadPool.shutdown();
//            List<Runnable> list = fixedThreadPool.shutdownNow();
//            System.out.println("未完task list size=" + list.size());
        }

这边需要注意的是shutdown方法的调用,在执行excute方法前,先判断是否已经shutdown了




newScheduledThreadPool:定长线程池,可以定时和周期的执行


ScheduledExecutorService scheduleThreadPool = Executors.newScheduledThreadPool(1);

        scheduleThreadPool.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("让我们跑起来,我只执行一次" );
            }
        },1, TimeUnit.SECONDS);
        final int[] idx = {0};
        scheduleThreadPool.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                idx[0] = idx[0] +1;
                System.out.println("让我们跑起来,循环间隔=" + idx[0]);
            }
        },1,1,TimeUnit.SECONDS);
//        scheduleThreadPool.shutdown();//这边调用shutdown没有问题

scheduleThreadPool:这边的schedule完全可以替换thread的定时操作了,^_^




newSingleThreadExecutor:单线程化的线程池,可以指定执行的顺序


ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();
        singleThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("我是一个单线程化线程池,ThreadName=" + Thread.currentThread().getName());
            }
        });
        //newSingleThreadScheduledExecutor创建的就是ScheduledThreadPoolExecutor
        /*
        * public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
            return new DelegatedScheduledExecutorService
                (new ScheduledThreadPoolExecutor(1));
             }
        */
       ScheduledExecutorService singleScheduleThreaPool= Executors.newSingleThreadScheduledExecutor();




4.遇到的问题总结


上面的常量操作只有数组可以进行自加的操作


ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();
        singleThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("我是一个单线程化线程池,ThreadName=" + Thread.currentThread().getName());
            }
        });
        //newSingleThreadScheduledExecutor创建的就是ScheduledThreadPoolExecutor
        /*
        * public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
            return new DelegatedScheduledExecutorService
                (new ScheduledThreadPoolExecutor(1));
             }
        */
       ScheduledExecutorService singleScheduleThreaPool= Executors.newSingleThreadScheduledExecutor();
        Future a =singleScheduleThreaPool.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("我执行了");
            }
        },1);
        try {
            System.out.println("给出结果了没=" + (Integer)a.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


这边需要注意excute和submit方法都可执行当前的task,submit可以指定返回的结果,如果不需要返回值,直接用excute方法

初次使用线程池,如有不足,大家多多见谅,多多指教^-^