Java多线程4 初识线程池

Java多线程目录

前言

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

    new Thread(new Runnable() {

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


    image.png

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的区别

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,826评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,968评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,234评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,562评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,611评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,482评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,271评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,166评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,608评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,814评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,926评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,644评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,249评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,866评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,991评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,063评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,871评论 2 354

推荐阅读更多精彩内容