ThreadPoolExecutor – Java 线程池示例

Java 线程池 管理工作线程池。它包含一个队列,用于存储等待执行的任务。我们可以使用 ThreadPoolExecutor 在 Java 中创建线程池。Java 线程池管理 Runnable 线程的集合。工作线程从队列中执行 Runnable 线程。java.util.concurrent.Executors 提供了创建 Java 中线程池的 java.util.concurrent.Executor 接口的工厂和支持方法。Executors 是一个实用类,通过各种工厂方法还提供了与 ExecutorService、ScheduledExecutorService、ThreadFactory 和 Callable 类一起使用的有用方法。让我们编写一个简单的程序来解释它的工作原理。首先,我们需要有一个 Runnable 类,命名为 WorkerThread.java

package com.journaldev.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;
    }
}

ExecutorService 示例

这是测试程序类 SimpleThreadPool.java,我们在其中使用 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");
    }
}

在上面的程序中,我们创建了一个由 5 个工作线程组成的固定大小的线程池。然后,我们提交了 10 个作业给此池,由于池大小为 5,它将开始处理 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

輸出確認池中有五個線程,命名從“pool-1-thread-1”到“pool-1-thread-5”,它們負責執行提交到池中的任務。

ThreadPoolExecutor範例

Executors類提供了使用ExecutorService的簡單實現,使用ThreadPoolExecutor,但ThreadPoolExecutor提供了更多功能。我們可以指定在創建ThreadPoolExecutor實例時活躍的線程數,還可以限制線程池的大小,並創建自己的RejectedExecutionHandler實現來處理無法放入工作隊列的任務。這是我們的RejectedExecutionHandler接口的自定義實現。

package com.journaldev.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.journaldev.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.journaldev.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 實現
        RejectedExecutionHandlerImpl rejectionHandler = new RejectedExecutionHandlerImpl();
        //取得 ThreadFactory 實現以使用
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        //建立 ThreadPoolExecutor
        ThreadPoolExecutor executorPool = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS, new ArrayBlockingQueue(2), threadFactory, rejectionHandler);
        //啟動監控執行緒
        MyMonitorThread monitor = new MyMonitorThread(executorPool, 3);
        Thread monitorThread = new Thread(monitor);
        monitorThread.start();
        //提交工作至執行緒池
        for(int i=0; i<10; i++){
            executorPool.execute(new WorkerThread("cmd"+i));
        }
        
        Thread.sleep(30000);
        //關閉池
        executorPool.shutdown();
        //關閉監視執行緒
        Thread.sleep(5000);
        monitor.shutdown();
        
    }
}

請注意,當初始化 ThreadPoolExecutor 時,我們將初始池大小設置為 2,最大池大小設置為 4,工作隊列大小設置為 2。因此,如果有 4 個運行中的任務且提交了更多任務,工作隊列將僅保留其中 2 個,其餘將由 RejectedExecutionHandlerImpl 處理。以下是確認上述語句的程式輸出。

pool-1-thread-1 Start. Command = cmd0
pool-1-thread-4 Start. Command = cmd5
cmd6 is rejected
pool-1-thread-3 Start. Command = cmd4
pool-1-thread-2 Start. Command = cmd1
cmd7 is rejected
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 類。在 Java 調度執行緒池執行者 中了解更多關於它們的信息。

Source:
https://www.digitalocean.com/community/tutorials/threadpoolexecutor-java-thread-pool-example-executorservice