Java多线程4 初识线程池

作者: 香沙小熊 | 来源:发表于2018-11-27 15:11 被阅读20次
    前言

    Java为什么引入线程池?
    创建线程示例

        new Thread(new Runnable() {
    
                @Override
                public void run() {
                
                }
            }).start();
    
    new Thread的弊端
    1. 每次new Thread新建对象性能差。
    2. 线程缺乏统一管理,可能无限制新建线程,相互之间竞争,及可能占用过多系统资源导致死机或oom。
    3. 缺乏更多功能,如定时执行、定期执行、线程中断。
    相比new Thread,Java提供的四种线程池的好处在于:
    1. 重用存在的线程,减少对象创建、消亡的开销,性能佳。
    2. 可有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞。
    3. 提供定时执行、定期执行、单线程、并发数控制等功能。

    1.Java四种线程池

    Java通过Executors提供四种线程池,分别为:
    newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
    newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
    newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
    newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。

    1.1 newFixedThreadPool

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

    public class ThreadPoolTest {
        public static void main(String[] args) {
    
            //固定线程池
            ExecutorService threadPool = Executors.newFixedThreadPool(3);
            for (int i = 1; i < 10; i++) {
                int finalI = i;
                threadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        for (int j = 1; j < 10; j++) {
                            try {
                                Thread.sleep(20);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            System.out.println(Thread.currentThread().getName() + " is looping of " + j + " for task of " + finalI
    
                            );
    
                        }
                    }
                });
            }
        }
    }
    
    pool-1-thread-3 is looping of 1 for task of 3
    pool-1-thread-2 is looping of 1 for task of 2
    pool-1-thread-1 is looping of 1 for task of 1
    pool-1-thread-3 is looping of 2 for task of 3
    pool-1-thread-1 is looping of 2 for task of 1
    pool-1-thread-2 is looping of 2 for task of 2
    pool-1-thread-3 is looping of 3 for task of 3
    pool-1-thread-1 is looping of 3 for task of 1
    pool-1-thread-2 is looping of 3 for task of 2
    pool-1-thread-3 is looping of 4 for task of 3
    pool-1-thread-2 is looping of 4 for task of 2
    pool-1-thread-1 is looping of 4 for task of 1
    pool-1-thread-1 is looping of 5 for task of 1
    pool-1-thread-2 is looping of 5 for task of 2
    pool-1-thread-3 is looping of 5 for task of 3
    pool-1-thread-1 is looping of 6 for task of 1
    pool-1-thread-3 is looping of 6 for task of 3
    pool-1-thread-2 is looping of 6 for task of 2
    pool-1-thread-1 is looping of 7 for task of 1
    pool-1-thread-3 is looping of 7 for task of 3
    pool-1-thread-2 is looping of 7 for task of 2
    pool-1-thread-1 is looping of 8 for task of 1
    pool-1-thread-3 is looping of 8 for task of 3
    pool-1-thread-2 is looping of 8 for task of 2
    pool-1-thread-1 is looping of 9 for task of 1
    pool-1-thread-2 is looping of 9 for task of 2
    pool-1-thread-3 is looping of 9 for task of 3
    pool-1-thread-1 is looping of 1 for task of 4
    pool-1-thread-2 is looping of 1 for task of 5
    pool-1-thread-3 is looping of 1 for task of 6
    pool-1-thread-1 is looping of 2 for task of 4
    pool-1-thread-2 is looping of 2 for task of 5
    pool-1-thread-3 is looping of 2 for task of 6
    pool-1-thread-1 is looping of 3 for task of 4
    pool-1-thread-2 is looping of 3 for task of 5
    pool-1-thread-3 is looping of 3 for task of 6
    pool-1-thread-3 is looping of 4 for task of 6
    pool-1-thread-1 is looping of 4 for task of 4
    pool-1-thread-2 is looping of 4 for task of 5
    pool-1-thread-3 is looping of 5 for task of 6
    pool-1-thread-1 is looping of 5 for task of 4
    pool-1-thread-2 is looping of 5 for task of 5
    pool-1-thread-2 is looping of 6 for task of 5
    pool-1-thread-1 is looping of 6 for task of 4
    pool-1-thread-3 is looping of 6 for task of 6
    pool-1-thread-2 is looping of 7 for task of 5
    pool-1-thread-3 is looping of 7 for task of 6
    pool-1-thread-1 is looping of 7 for task of 4
    pool-1-thread-1 is looping of 8 for task of 4
    pool-1-thread-3 is looping of 8 for task of 6
    pool-1-thread-2 is looping of 8 for task of 5
    pool-1-thread-3 is looping of 9 for task of 6
    pool-1-thread-2 is looping of 9 for task of 5
    pool-1-thread-1 is looping of 9 for task of 4
    pool-1-thread-2 is looping of 1 for task of 8
    pool-1-thread-1 is looping of 1 for task of 9
    pool-1-thread-3 is looping of 1 for task of 7
    pool-1-thread-1 is looping of 2 for task of 9
    pool-1-thread-2 is looping of 2 for task of 8
    pool-1-thread-3 is looping of 2 for task of 7
    pool-1-thread-1 is looping of 3 for task of 9
    pool-1-thread-2 is looping of 3 for task of 8
    pool-1-thread-3 is looping of 3 for task of 7
    pool-1-thread-1 is looping of 4 for task of 9
    pool-1-thread-2 is looping of 4 for task of 8
    pool-1-thread-3 is looping of 4 for task of 7
    pool-1-thread-2 is looping of 5 for task of 8
    pool-1-thread-3 is looping of 5 for task of 7
    pool-1-thread-1 is looping of 5 for task of 9
    pool-1-thread-2 is looping of 6 for task of 8
    pool-1-thread-1 is looping of 6 for task of 9
    pool-1-thread-3 is looping of 6 for task of 7
    pool-1-thread-3 is looping of 7 for task of 7
    pool-1-thread-1 is looping of 7 for task of 9
    pool-1-thread-2 is looping of 7 for task of 8
    pool-1-thread-3 is looping of 8 for task of 7
    pool-1-thread-1 is looping of 8 for task of 9
    pool-1-thread-2 is looping of 8 for task of 8
    pool-1-thread-3 is looping of 9 for task of 7
    pool-1-thread-2 is looping of 9 for task of 8
    pool-1-thread-1 is looping of 9 for task of 9
    

    定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()

    1.2 newFixedThreadPool

    创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

    public class ThreadPoolTest {
        public static void main(String[] args) {
            //固定线程池
            ExecutorService threadPool = Executors.newSingleThreadExecutor();
            for (int i = 1; i < 10; i++) {
                int finalI = i;
                threadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        for (int j = 1; j < 10; j++) {
                            try {
                                Thread.sleep(20);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            System.out.println(Thread.currentThread().getName() + " is looping of " + j + " for task of " + finalI
    
                            );
    
                        }
                    }
                });
            }
    
        }
    }
    
    pool-1-thread-1 is looping of 1 for task of 1
    pool-1-thread-1 is looping of 2 for task of 1
    pool-1-thread-1 is looping of 3 for task of 1
    pool-1-thread-1 is looping of 4 for task of 1
    pool-1-thread-1 is looping of 5 for task of 1
    pool-1-thread-1 is looping of 6 for task of 1
    pool-1-thread-1 is looping of 7 for task of 1
    pool-1-thread-1 is looping of 8 for task of 1
    pool-1-thread-1 is looping of 9 for task of 1
    pool-1-thread-1 is looping of 1 for task of 2
    pool-1-thread-1 is looping of 2 for task of 2
    pool-1-thread-1 is looping of 3 for task of 2
    pool-1-thread-1 is looping of 4 for task of 2
    pool-1-thread-1 is looping of 5 for task of 2
    pool-1-thread-1 is looping of 6 for task of 2
    pool-1-thread-1 is looping of 7 for task of 2
    pool-1-thread-1 is looping of 8 for task of 2
    pool-1-thread-1 is looping of 9 for task of 2
    pool-1-thread-1 is looping of 1 for task of 3
    pool-1-thread-1 is looping of 2 for task of 3
    pool-1-thread-1 is looping of 3 for task of 3
    pool-1-thread-1 is looping of 4 for task of 3
    pool-1-thread-1 is looping of 5 for task of 3
    pool-1-thread-1 is looping of 6 for task of 3
    pool-1-thread-1 is looping of 7 for task of 3
    pool-1-thread-1 is looping of 8 for task of 3
    pool-1-thread-1 is looping of 9 for task of 3
    pool-1-thread-1 is looping of 1 for task of 4
    pool-1-thread-1 is looping of 2 for task of 4
    pool-1-thread-1 is looping of 3 for task of 4
    pool-1-thread-1 is looping of 4 for task of 4
    pool-1-thread-1 is looping of 5 for task of 4
    pool-1-thread-1 is looping of 6 for task of 4
    pool-1-thread-1 is looping of 7 for task of 4
    pool-1-thread-1 is looping of 8 for task of 4
    pool-1-thread-1 is looping of 9 for task of 4
    pool-1-thread-1 is looping of 1 for task of 5
    pool-1-thread-1 is looping of 2 for task of 5
    pool-1-thread-1 is looping of 3 for task of 5
    pool-1-thread-1 is looping of 4 for task of 5
    pool-1-thread-1 is looping of 5 for task of 5
    pool-1-thread-1 is looping of 6 for task of 5
    pool-1-thread-1 is looping of 7 for task of 5
    pool-1-thread-1 is looping of 8 for task of 5
    pool-1-thread-1 is looping of 9 for task of 5
    pool-1-thread-1 is looping of 1 for task of 6
    pool-1-thread-1 is looping of 2 for task of 6
    pool-1-thread-1 is looping of 3 for task of 6
    pool-1-thread-1 is looping of 4 for task of 6
    pool-1-thread-1 is looping of 5 for task of 6
    pool-1-thread-1 is looping of 6 for task of 6
    pool-1-thread-1 is looping of 7 for task of 6
    pool-1-thread-1 is looping of 8 for task of 6
    pool-1-thread-1 is looping of 9 for task of 6
    pool-1-thread-1 is looping of 1 for task of 7
    pool-1-thread-1 is looping of 2 for task of 7
    pool-1-thread-1 is looping of 3 for task of 7
    pool-1-thread-1 is looping of 4 for task of 7
    pool-1-thread-1 is looping of 5 for task of 7
    pool-1-thread-1 is looping of 6 for task of 7
    pool-1-thread-1 is looping of 7 for task of 7
    pool-1-thread-1 is looping of 8 for task of 7
    pool-1-thread-1 is looping of 9 for task of 7
    pool-1-thread-1 is looping of 1 for task of 8
    pool-1-thread-1 is looping of 2 for task of 8
    pool-1-thread-1 is looping of 3 for task of 8
    pool-1-thread-1 is looping of 4 for task of 8
    pool-1-thread-1 is looping of 5 for task of 8
    pool-1-thread-1 is looping of 6 for task of 8
    pool-1-thread-1 is looping of 7 for task of 8
    pool-1-thread-1 is looping of 8 for task of 8
    pool-1-thread-1 is looping of 9 for task of 8
    pool-1-thread-1 is looping of 1 for task of 9
    pool-1-thread-1 is looping of 2 for task of 9
    pool-1-thread-1 is looping of 3 for task of 9
    pool-1-thread-1 is looping of 4 for task of 9
    pool-1-thread-1 is looping of 5 for task of 9
    pool-1-thread-1 is looping of 6 for task of 9
    pool-1-thread-1 is looping of 7 for task of 9
    pool-1-thread-1 is looping of 8 for task of 9
    pool-1-thread-1 is looping of 9 for task of 9
    

    结果依次输出,相当于顺序执行各个任务。
    现行大多数GUI程序都是单线程的。Android中单线程可用于数据库操作,文件操作,应用批量安装,应用批量删除等不适合并发但可能IO阻塞性及影响UI线程响应的操作。

    1.3 newCachedThreadPool

    创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程

    public class ThreadPoolTest {
        public static void main(String[] args) {
            //固定线程池
            ExecutorService threadPool = Executors.newCachedThreadPool();
            for (int i = 1; i < 10; i++) {
                int finalI = i;
                threadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        for (int j = 1; j < 10; j++) {
                            try {
                                Thread.sleep(20);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            System.out.println(Thread.currentThread().getName() + " is looping of " + j + " for task of " + finalI
    
                            );
    
                        }
                    }
                });
            }
    
        }
    }
    
    pool-1-thread-2 is looping of 1 for task of 2
    pool-1-thread-1 is looping of 1 for task of 1
    pool-1-thread-8 is looping of 1 for task of 8
    pool-1-thread-9 is looping of 1 for task of 9
    pool-1-thread-6 is looping of 1 for task of 6
    pool-1-thread-3 is looping of 1 for task of 3
    pool-1-thread-7 is looping of 1 for task of 7
    pool-1-thread-4 is looping of 1 for task of 4
    pool-1-thread-5 is looping of 1 for task of 5
    pool-1-thread-6 is looping of 2 for task of 6
    pool-1-thread-5 is looping of 2 for task of 5
    pool-1-thread-2 is looping of 2 for task of 2
    pool-1-thread-1 is looping of 2 for task of 1
    pool-1-thread-7 is looping of 2 for task of 7
    pool-1-thread-8 is looping of 2 for task of 8
    pool-1-thread-3 is looping of 2 for task of 3
    pool-1-thread-9 is looping of 2 for task of 9
    pool-1-thread-4 is looping of 2 for task of 4
    pool-1-thread-5 is looping of 3 for task of 5
    pool-1-thread-9 is looping of 3 for task of 9
    pool-1-thread-1 is looping of 3 for task of 1
    pool-1-thread-2 is looping of 3 for task of 2
    pool-1-thread-8 is looping of 3 for task of 8
    pool-1-thread-3 is looping of 3 for task of 3
    pool-1-thread-7 is looping of 3 for task of 7
    pool-1-thread-6 is looping of 3 for task of 6
    pool-1-thread-4 is looping of 3 for task of 4
    pool-1-thread-2 is looping of 4 for task of 2
    pool-1-thread-6 is looping of 4 for task of 6
    pool-1-thread-4 is looping of 4 for task of 4
    pool-1-thread-7 is looping of 4 for task of 7
    pool-1-thread-1 is looping of 4 for task of 1
    pool-1-thread-9 is looping of 4 for task of 9
    pool-1-thread-3 is looping of 4 for task of 3
    pool-1-thread-5 is looping of 4 for task of 5
    pool-1-thread-8 is looping of 4 for task of 8
    pool-1-thread-6 is looping of 5 for task of 6
    pool-1-thread-9 is looping of 5 for task of 9
    pool-1-thread-5 is looping of 5 for task of 5
    pool-1-thread-8 is looping of 5 for task of 8
    pool-1-thread-3 is looping of 5 for task of 3
    pool-1-thread-1 is looping of 5 for task of 1
    pool-1-thread-7 is looping of 5 for task of 7
    pool-1-thread-4 is looping of 5 for task of 4
    pool-1-thread-2 is looping of 5 for task of 2
    pool-1-thread-6 is looping of 6 for task of 6
    pool-1-thread-2 is looping of 6 for task of 2
    pool-1-thread-4 is looping of 6 for task of 4
    pool-1-thread-7 is looping of 6 for task of 7
    pool-1-thread-3 is looping of 6 for task of 3
    pool-1-thread-1 is looping of 6 for task of 1
    pool-1-thread-5 is looping of 6 for task of 5
    pool-1-thread-8 is looping of 6 for task of 8
    pool-1-thread-9 is looping of 6 for task of 9
    pool-1-thread-4 is looping of 7 for task of 4
    pool-1-thread-3 is looping of 7 for task of 3
    pool-1-thread-5 is looping of 7 for task of 5
    pool-1-thread-1 is looping of 7 for task of 1
    pool-1-thread-9 is looping of 7 for task of 9
    pool-1-thread-8 is looping of 7 for task of 8
    pool-1-thread-7 is looping of 7 for task of 7
    pool-1-thread-6 is looping of 7 for task of 6
    pool-1-thread-2 is looping of 7 for task of 2
    pool-1-thread-9 is looping of 8 for task of 9
    pool-1-thread-5 is looping of 8 for task of 5
    pool-1-thread-7 is looping of 8 for task of 7
    pool-1-thread-1 is looping of 8 for task of 1
    pool-1-thread-3 is looping of 8 for task of 3
    pool-1-thread-4 is looping of 8 for task of 4
    pool-1-thread-8 is looping of 8 for task of 8
    pool-1-thread-6 is looping of 8 for task of 6
    pool-1-thread-2 is looping of 8 for task of 2
    pool-1-thread-5 is looping of 9 for task of 5
    pool-1-thread-2 is looping of 9 for task of 2
    pool-1-thread-4 is looping of 9 for task of 4
    pool-1-thread-6 is looping of 9 for task of 6
    pool-1-thread-8 is looping of 9 for task of 8
    pool-1-thread-3 is looping of 9 for task of 3
    pool-1-thread-1 is looping of 9 for task of 1
    pool-1-thread-7 is looping of 9 for task of 7
    pool-1-thread-9 is looping of 9 for task of 9
    

    线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。

    1.4 newScheduledThreadPool
    public class ThreadPoolTest {
        public static void main(String[] args) {
    
            System.out.println("init");
    
            Executors.newScheduledThreadPool(3).schedule(
                    new Runnable() {
                        @Override
                        public void run() {
                            System.out.println("Done");
                        }
                    }, 3, TimeUnit.SECONDS
            );
        }
    }
    
    init
    Done
    

    表示延迟3秒执行。

    定期执行
    public class ThreadPoolTest {
        public static void main(String[] args) {
    
            Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
    
                    System.out.println("每三秒执行一次");
                }
            },2,3,TimeUnit.SECONDS);
    
        }
    }
    
    每三秒执行一次
    每三秒执行一次
    每三秒执行一次
    每三秒执行一次
    省略...
    

    2 关闭线程池

    shutdown()

    public class ThreadPoolTest {
        public static void main(String[] args) {
    
            //固定线程池
            ExecutorService threadPool = Executors.newFixedThreadPool(3);
    
            //缓存线程池 池中的线程数量
            //ExecutorService threadPool = Executors.newCachedThreadPool();
    
            //单个线程
            //ExecutorService threadPool = Executors.newSingleThreadExecutor();
    
            for (int i = 1; i < 10; i++) {
                int finalI = i;
                threadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        for (int j = 1; j < 10; j++) {
                            try {
                                Thread.sleep(20);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            System.out.println(Thread.currentThread().getName() + " is looping of " + j + " for task of " + finalI
    
                            );
    
                        }
                    }
                });
            }
            threadPool.shutdown();
    
    
        }
    }
    
    pool-1-thread-1 is looping of 1 for task of 1
    pool-1-thread-2 is looping of 1 for task of 2
    pool-1-thread-3 is looping of 1 for task of 3
    pool-1-thread-1 is looping of 2 for task of 1
    pool-1-thread-3 is looping of 2 for task of 3
    pool-1-thread-2 is looping of 2 for task of 2
    pool-1-thread-1 is looping of 3 for task of 1
    pool-1-thread-2 is looping of 3 for task of 2
    pool-1-thread-3 is looping of 3 for task of 3
    pool-1-thread-1 is looping of 4 for task of 1
    pool-1-thread-3 is looping of 4 for task of 3
    pool-1-thread-2 is looping of 4 for task of 2
    pool-1-thread-3 is looping of 5 for task of 3
    pool-1-thread-1 is looping of 5 for task of 1
    pool-1-thread-2 is looping of 5 for task of 2
    pool-1-thread-3 is looping of 6 for task of 3
    pool-1-thread-1 is looping of 6 for task of 1
    pool-1-thread-2 is looping of 6 for task of 2
    pool-1-thread-3 is looping of 7 for task of 3
    pool-1-thread-1 is looping of 7 for task of 1
    pool-1-thread-2 is looping of 7 for task of 2
    pool-1-thread-3 is looping of 8 for task of 3
    pool-1-thread-1 is looping of 8 for task of 1
    pool-1-thread-2 is looping of 8 for task of 2
    pool-1-thread-1 is looping of 9 for task of 1
    pool-1-thread-3 is looping of 9 for task of 3
    pool-1-thread-2 is looping of 9 for task of 2
    pool-1-thread-1 is looping of 1 for task of 4
    pool-1-thread-3 is looping of 1 for task of 5
    pool-1-thread-2 is looping of 1 for task of 6
    pool-1-thread-1 is looping of 2 for task of 4
    pool-1-thread-3 is looping of 2 for task of 5
    pool-1-thread-2 is looping of 2 for task of 6
    pool-1-thread-1 is looping of 3 for task of 4
    pool-1-thread-3 is looping of 3 for task of 5
    pool-1-thread-2 is looping of 3 for task of 6
    pool-1-thread-1 is looping of 4 for task of 4
    pool-1-thread-3 is looping of 4 for task of 5
    pool-1-thread-2 is looping of 4 for task of 6
    pool-1-thread-3 is looping of 5 for task of 5
    pool-1-thread-1 is looping of 5 for task of 4
    pool-1-thread-2 is looping of 5 for task of 6
    pool-1-thread-3 is looping of 6 for task of 5
    pool-1-thread-1 is looping of 6 for task of 4
    pool-1-thread-2 is looping of 6 for task of 6
    pool-1-thread-3 is looping of 7 for task of 5
    pool-1-thread-1 is looping of 7 for task of 4
    pool-1-thread-2 is looping of 7 for task of 6
    pool-1-thread-3 is looping of 8 for task of 5
    pool-1-thread-1 is looping of 8 for task of 4
    pool-1-thread-2 is looping of 8 for task of 6
    pool-1-thread-3 is looping of 9 for task of 5
    pool-1-thread-1 is looping of 9 for task of 4
    pool-1-thread-2 is looping of 9 for task of 6
    pool-1-thread-1 is looping of 1 for task of 8
    pool-1-thread-2 is looping of 1 for task of 9
    pool-1-thread-3 is looping of 1 for task of 7
    pool-1-thread-1 is looping of 2 for task of 8
    pool-1-thread-2 is looping of 2 for task of 9
    pool-1-thread-3 is looping of 2 for task of 7
    pool-1-thread-1 is looping of 3 for task of 8
    pool-1-thread-2 is looping of 3 for task of 9
    pool-1-thread-3 is looping of 3 for task of 7
    pool-1-thread-1 is looping of 4 for task of 8
    pool-1-thread-2 is looping of 4 for task of 9
    pool-1-thread-3 is looping of 4 for task of 7
    pool-1-thread-2 is looping of 5 for task of 9
    pool-1-thread-3 is looping of 5 for task of 7
    pool-1-thread-1 is looping of 5 for task of 8
    pool-1-thread-2 is looping of 6 for task of 9
    pool-1-thread-3 is looping of 6 for task of 7
    pool-1-thread-1 is looping of 6 for task of 8
    pool-1-thread-2 is looping of 7 for task of 9
    pool-1-thread-3 is looping of 7 for task of 7
    pool-1-thread-1 is looping of 7 for task of 8
    pool-1-thread-3 is looping of 8 for task of 7
    pool-1-thread-1 is looping of 8 for task of 8
    pool-1-thread-2 is looping of 8 for task of 9
    pool-1-thread-3 is looping of 9 for task of 7
    pool-1-thread-1 is looping of 9 for task of 8
    pool-1-thread-2 is looping of 9 for task of 9
    

    shutdownNow

    public class ThreadPoolTest {
        public static void main(String[] args) {
    
            //固定线程池
            ExecutorService threadPool = Executors.newFixedThreadPool(3);
    
            //缓存线程池 池中的线程数量
            //ExecutorService threadPool = Executors.newCachedThreadPool();
    
            //单个线程
            //ExecutorService threadPool = Executors.newSingleThreadExecutor();
    
            for (int i = 1; i < 10; i++) {
                int finalI = i;
                threadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        for (int j = 1; j < 10; j++) {
                            try {
                                Thread.sleep(20);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            System.out.println(Thread.currentThread().getName() + " is looping of " + j + " for task of " + finalI
    
                            );
    
                        }
                    }
                });
            }
            threadPool.shutdownNow();
    
    
        }
    }
    
    java.lang.InterruptedException: sleep interrupted
        at java.lang.Thread.sleep(Native Method)
        at ThreadPoolTest$1.run(ThreadPoolTest.java:23)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
    java.lang.InterruptedException: sleep interrupted
    pool-1-thread-3 is looping of 1 for task of 3
        at java.lang.Thread.sleep(Native Method)
        at ThreadPoolTest$1.run(ThreadPoolTest.java:23)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
    pool-1-thread-2 is looping of 1 for task of 2
    java.lang.InterruptedException: sleep interrupted
        at java.lang.Thread.sleep(Native Method)
        at ThreadPoolTest$1.run(ThreadPoolTest.java:23)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
    pool-1-thread-1 is looping of 1 for task of 1
    pool-1-thread-3 is looping of 2 for task of 3
    pool-1-thread-1 is looping of 2 for task of 1
    pool-1-thread-2 is looping of 2 for task of 2
    pool-1-thread-2 is looping of 3 for task of 2
    pool-1-thread-1 is looping of 3 for task of 1
    pool-1-thread-3 is looping of 3 for task of 3
    pool-1-thread-2 is looping of 4 for task of 2
    pool-1-thread-3 is looping of 4 for task of 3
    pool-1-thread-1 is looping of 4 for task of 1
    pool-1-thread-2 is looping of 5 for task of 2
    pool-1-thread-1 is looping of 5 for task of 1
    pool-1-thread-3 is looping of 5 for task of 3
    pool-1-thread-1 is looping of 6 for task of 1
    pool-1-thread-2 is looping of 6 for task of 2
    pool-1-thread-3 is looping of 6 for task of 3
    pool-1-thread-1 is looping of 7 for task of 1
    pool-1-thread-3 is looping of 7 for task of 3
    pool-1-thread-2 is looping of 7 for task of 2
    pool-1-thread-1 is looping of 8 for task of 1
    pool-1-thread-3 is looping of 8 for task of 3
    pool-1-thread-2 is looping of 8 for task of 2
    pool-1-thread-3 is looping of 9 for task of 3
    pool-1-thread-2 is looping of 9 for task of 2
    pool-1-thread-1 is looping of 9 for task of 1
    
    2.1 shutdown和shutdownNow的区别

    shutdown只是将线程池的状态设置为SHUTWDOWN状态,正在执行的任务会继续执行下去,没有被执行的则中断。而shutdownNow则是将线程池的状态设置为STOP,正在执行的任务则被停止,没被执行任务的则返回。

    2.3 源码分析shutdown和shutdownNow

    1.shutdown源码

        public void shutdown() {
            final ReentrantLock mainLock = this.mainLock;
            mainLock.lock();
            try {
                checkShutdownAccess();
                advanceRunState(SHUTDOWN);
                interruptIdleWorkers();
                onShutdown(); // hook for ScheduledThreadPoolExecutor
            } finally {
                mainLock.unlock();
            }
            tryTerminate();
        }
    

    2.shutdownNow源码

        public List<Runnable> shutdownNow() {
            List<Runnable> tasks;
            final ReentrantLock mainLock = this.mainLock;
            mainLock.lock();
            try {
                checkShutdownAccess();
                advanceRunState(STOP);
                interruptWorkers();
                tasks = drainQueue();
            } finally {
                mainLock.unlock();
            }
            tryTerminate();
            return tasks;
        }
    

    从源码可以很清晰的看出两者的区别,shutdown使用了以后会置状态为SHUTDOWN,而shutdownNow为STOP。此外,shutdownNow会返回任务列表。

    2.3 线程状态知识延伸

    在ThreadPoolExecutor中定义了关于线程状态的几个变量如下:

    // runState is stored in the high-order bits
    private static final int RUNNING = -1 << COUNT_BITS;
    private static final int SHUTDOWN = 0 << COUNT_BITS;
    private static final int STOP = 1 << COUNT_BITS;
    private static final int TIDYING = 2 << COUNT_BITS;
    private static final int TERMINATED = 3 << COUNT_BITS;

    1.当创建线程池后,初始时,线程池处于RUNNING状态,此时线程池中的任务为0;
    2.如果调用了shutdown()方法,则线程池处于SHUTDOWN状态,此时线程池不能够接受新的任务,它会等待所有任务执行完毕;
    3.如果调用了shutdownNow()方法,则线程池处于STOP状态,此时线程池不能接受新的任务,并且会去尝试终止正在执行的任务;
    4.当所有的任务已终止,ctl记录的”任务数量”为0,线程池会变为TIDYING状态。接着会执行terminated()函数。
    5.线程池处在TIDYING状态时,执行完terminated()之后,就会由 TIDYING -> TERMINATED,线程池被设置为TERMINATED状态。

    总结

    线程池的作用:

    线程池作用就是限制系统中执行线程的数量。
    根据系统的环境情况,可以自动或手动设置线程数量,达到运行的最佳效果;少了浪费了系统资源,多了造成系统拥挤效率不高。用线程池控制线程数量,其他线程排队等候。一个任务执行完毕,再从队列的中取最前面的任务开始执行。若队列中没有等待进程,线程池的这一资源处于等待。当一个新任务需要运行时,如果线程池 中有等待的工作线程,就可以开始运行了;否则进入等待队列。

    为什么要用线程池:

    1.减少了创建和销毁线程的次数,每个工作线程都可以被重复利用,可执行多个任务。
    2.可以根据系统的承受能力,调整线程池中工作线线程的数目,防止因为消耗过多的内存,而把服务器累趴下(每个线程需要大约1MB内存,线程开的越多,消耗的内存也就越大,最后死机)。

    特别感谢:

    星辰之力Java 四种线程池
    一句话说明白Java线程池中shutdown和shutdownNow的区别

    相关文章

      网友评论

        本文标题:Java多线程4 初识线程池

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