• Java线程和多线程(十二)——线程池基础


    Java 线程池管理多个工作线程,其中包含了一个队列,包含着所有等待被执行的任务。开发者可以通过使用ThreadPoolExecutor来在Java中创建线程池。

    线程池是Java中多线程的一个重要概念,因为通过Thread模型来控制多线程是非常麻烦以及易错的一个过程。过多的释放线程会造成线程调度的变慢以及过度的消耗内存。而频繁的创建线程,也没有很好的复用线程,所以有了线程池的概念。Java中的线程池就是ExecutorService
    其中包含了一些基本的关闭,执行等功能

    ExecutorService举例

    java.util.concurrent.Executors提供了java.util.concurrent.Executor接口的实现,并且用来提供线程池服务。参考如下代码:

    package com.sapphire.threadpool;
    
    public class WorkerThread implements Runnable {
    
        private String command;
    
        public WorkerThread(String s){
            this.command=s;
        }
    
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+" Start. Command = "+command);
            processCommand();
            System.out.println(Thread.currentThread().getName()+" End.");
        }
    
        private void processCommand() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        @Override
        public String toString(){
            return this.command;
        }
    }

    上面的代码是一个简单的实现了RunnableWorkThread。下面展示的是线程池代码,通过Executors框架创建的固定线程数的线程池。

    package com.journaldev.threadpool;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class SimpleThreadPool {
    
        public static void main(String[] args) {
            ExecutorService executor = Executors.newFixedThreadPool(5);
            for (int i = 0; i < 10; i++) {
                Runnable worker = new WorkerThread("" + i);
                executor.execute(worker);
              }
            executor.shutdown();
            while (!executor.isTerminated()) {
            }
            System.out.println("Finished all threads");
        }
    }

    上面个程序中的ExecutorService executor就是一个线程池,其调用的函数Executors.newFixedThreadPool(int size)函数来生成固定的线程数的一个线程池。在程序中,我们通过一个for循环提交了10个任务,因为我们配置了线程池的大小,所以其中的线程数最大始终是5不会出现无限创建线程的那种情况,当同时有其他的任务提交到线程池的时候,线程池会持续的等待,直到有一个任务完成,那么另一个任务就会从等待队列里面出来,进入执行队列来执行。

    下面是上面程序的输出内容:

    pool-1-thread-2 Start. Command = 1
    pool-1-thread-4 Start. Command = 3
    pool-1-thread-1 Start. Command = 0
    pool-1-thread-3 Start. Command = 2
    pool-1-thread-5 Start. Command = 4
    pool-1-thread-4 End.
    pool-1-thread-5 End.
    pool-1-thread-1 End.
    pool-1-thread-3 End.
    pool-1-thread-3 Start. Command = 8
    pool-1-thread-2 End.
    pool-1-thread-2 Start. Command = 9
    pool-1-thread-1 Start. Command = 7
    pool-1-thread-5 Start. Command = 6
    pool-1-thread-4 Start. Command = 5
    pool-1-thread-2 End.
    pool-1-thread-4 End.
    pool-1-thread-3 End.
    pool-1-thread-5 End.
    pool-1-thread-1 End.
    Finished all threads

    其中输出的内容也说明了在线程池中有5个线程,名字从pool-1-thread-1pool-1-thread-5,由叫这5个名字的线程负责执行提交到线程池的任务。

    ThreadPoolExecutor举例

    Executors类通过ThreadPoolExecutor提供了ExecutorService的简单实现,但是,ThreadPoolExecutor提供的特性更多。我们可以在创建ThreadPoolExecutor
    时指定线程池的大小,也可以定制RejectedExecutionHandler的实现来处理无法加入工作队列的任务。

    下面是我们的自定义的RejectedExecutionHandler:

    package com.sapphire.threadpool;
    
    import java.util.concurrent.RejectedExecutionHandler;
    import java.util.concurrent.ThreadPoolExecutor;
    
    public class RejectedExecutionHandlerImpl implements RejectedExecutionHandler {
    
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            System.out.println(r.toString() + " is rejected");
        }
    }

    ThreadPoolExecutor会提供一些方法,令开发者可以知道目前线程池的状态,比如,线程池大小,活跃的线程数,任务队列长度等信息。所以,下面我写了一个监控线程来定期展示线程池的状态信息。

    package com.sapphire.threadpool;
    
    import java.util.concurrent.ThreadPoolExecutor;
    
    public class MyMonitorThread implements Runnable
    {
        private ThreadPoolExecutor executor;
        private int seconds;
        private boolean run=true;
    
        public MyMonitorThread(ThreadPoolExecutor executor, int delay)
        {
            this.executor = executor;
            this.seconds=delay;
        }
        public void shutdown(){
            this.run=false;
        }
        @Override
        public void run()
        {
            while(run){
                    System.out.println(
                        String.format("[monitor] [%d/%d] Active: %d, Completed: %d, Task: %d, isShutdown: %s, isTerminated: %s",
                            this.executor.getPoolSize(),
                            this.executor.getCorePoolSize(),
                            this.executor.getActiveCount(),
                            this.executor.getCompletedTaskCount(),
                            this.executor.getTaskCount(),
                            this.executor.isShutdown(),
                            this.executor.isTerminated()));
                    try {
                        Thread.sleep(seconds*1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
            }
    
        }
    }

    下面是使用ThreadPoolExecutor的实现方案。

    package com.sapphire.threadpool;
    
    import java.util.concurrent.ArrayBlockingQueue;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ThreadFactory;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    
    public class WorkerPool {
    
        public static void main(String args[]) throws InterruptedException{
            //RejectedExecutionHandler implementation
            RejectedExecutionHandlerImpl rejectionHandler = new RejectedExecutionHandlerImpl();
            //Get the ThreadFactory implementation to use
            ThreadFactory threadFactory = Executors.defaultThreadFactory();
            //creating the ThreadPoolExecutor
            ThreadPoolExecutor executorPool = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2), threadFactory, rejectionHandler);
            //start the monitoring thread
            MyMonitorThread monitor = new MyMonitorThread(executorPool, 3);
            Thread monitorThread = new Thread(monitor);
            monitorThread.start();
            //submit work to the thread pool
            for(int i=0; i<10; i++){
                executorPool.execute(new WorkerThread("cmd"+i));
            }
    
            Thread.sleep(30000);
            //shut down the pool
            executorPool.shutdown();
            //shut down the monitor thread
            Thread.sleep(5000);
            monitor.shutdown();
    
        }
    }

    需要注意的是,当我们在创建ThreadPoolExecutor的时候,我们限制了线程池的大小最小为2,最大大小为4,而工作队列长度为2。所以如果线程池中4个运行的任务的时候,再提交更多任务的时候,则至多只能提交两个处于等待状态的任务。如果再提交更多的话,则会由RejectedExecutionHandlerImpl来处理。

    cmd8 is rejected
    cmd9 is rejected
    [monitor] [0/2] Active: 4, Completed: 0, Task: 6, isShutdown: false, isTerminated: false
    [monitor] [4/2] Active: 4, Completed: 0, Task: 6, isShutdown: false, isTerminated: false
    pool-1-thread-4 End.
    pool-1-thread-1 End.
    pool-1-thread-2 End.
    pool-1-thread-3 End.
    pool-1-thread-1 Start. Command = cmd3
    pool-1-thread-4 Start. Command = cmd2
    [monitor] [4/2] Active: 2, Completed: 4, Task: 6, isShutdown: false, isTerminated: false
    [monitor] [4/2] Active: 2, Completed: 4, Task: 6, isShutdown: false, isTerminated: false
    pool-1-thread-1 End.
    pool-1-thread-4 End.
    [monitor] [4/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
    [monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
    [monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
    [monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
    [monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
    [monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
    [monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: true, isTerminated: true
    [monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: true, isTerminated: true

    可以观察线程池在各个状态,如:活跃状态数,任务的完成数等等信息的变化。我们通过调用shutdown()方法来结束提交任务的执行,并结束了线程池。

    如果开发者希望来延迟执行一个任务,或者定期执行一个任务的话,开发者可以使用ScheduledThreadPoolExecutor类来完成这个功能。

  • 相关阅读:
    UVA 11776
    NEFU 117
    hihocoder 1331
    NEFU 84
    虚拟机类加载机制
    动态规划 -- 01背包问题和完全背包问题
    动态规划 ---- 最长回文子串
    动态规划 ---- 最长公共子序列(Longest Common Subsequence, LCS)
    动态规划 ---- 最长不下降子序列(Longest Increasing Sequence, LIS)
    动态规划(Dynamic Programming, DP)---- 最大连续子序列和 & 力扣53. 最大子序和
  • 原文地址:https://www.cnblogs.com/qitian1/p/6461515.html
Copyright © 2020-2023  润新知