`

线程池实例:使用Executors和ThreadPoolExecutor

阅读更多

        线程池负责管理工作线程,包含一个等待执行的任务队列。线程池的任务队列是一个Runnable集合,工作线程负责从任务队列中取出并执行Runnable对象。

        java.util.concurrent.executors 提供了 java.util.concurrent.executor 接口的一个Java实现,可以创建线程池。下面是一个简单示例:

        首先创建一个Runable 类:

WorkerThread.java

package com.bijian.study;

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;
    }
}

        下面是一个测试程序,从 Executors 框架中创建固定大小的线程池:

SimpleThreadPool.java

package com.bijian.study;

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-1 Start. Command = 0
pool-1-thread-4 Start. Command = 3
pool-1-thread-5 Start. Command = 4
pool-1-thread-2 Start. Command = 1
pool-1-thread-3 Start. Command = 2
pool-1-thread-2 End.
pool-1-thread-4 End.
pool-1-thread-1 End.
pool-1-thread-5 End.
pool-1-thread-3 End.
pool-1-thread-5 Start. Command = 8
pool-1-thread-1 Start. Command = 7
pool-1-thread-2 Start. Command = 5
pool-1-thread-4 Start. Command = 6
pool-1-thread-3 Start. Command = 9
pool-1-thread-3 End.
pool-1-thread-2 End.
pool-1-thread-1 End.
pool-1-thread-4 End.
pool-1-thread-5 End.
Finished all threads

        从输出结果看,线程池中有五个名为“pool-1-thread-1”…“pool-1-thread-5”的工作线程负责执行提交的任务。

        Executors 类使用 ExecutorService  提供了一个 ThreadPoolExecutor 的简单实现,但ThreadPoolExecutor 提供的功能远不止这些。我们可以指定创建 ThreadPoolExecutor 实例时活跃的线程数,并且可以限制线程池的大小,还可以创建自己的 RejectedExecutionHandler 实现来处理不适合放在工作队列里的任务。

        下面是一个 RejectedExecutionHandler 接口的自定义实现:

RejectedExecutionHandlerImpl.java

package com.bijian.study;

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 提供了一些方法,可以查看执行状态、线程池大小、活动线程数和任务数。所以,我通过一个监视线程在固定间隔输出执行信息。

MyMonitorThread.java

package com.bijian.study;

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 的线程池实现示例:

WorkerPool.java

package com.bijian.study;

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个任务正在运行,而此时又有新任务提交,工作队列将只存储2个任务,其他任务将交由RejectedExecutionHandlerImpl 处理。

        程序执行的结果如下,确认了上面的结论:

pool-1-thread-2 Start. Command = cmd1
cmd6 is rejected
cmd7 is rejected
cmd8 is rejected
cmd9 is rejected
pool-1-thread-4 Start. Command = cmd5
pool-1-thread-1 Start. Command = cmd0
pool-1-thread-3 Start. Command = cmd4
[monitor] [0/2] Active: 0, Completed: 0, Task: 6, isShutdown: false, isTerminated: false
[monitor] [4/2] Active: 4, Completed: 0, Task: 6, isShutdown: false, isTerminated: false
pool-1-thread-2 End.
pool-1-thread-4 End.
pool-1-thread-1 End.
pool-1-thread-3 End.
pool-1-thread-4 Start. Command = cmd3
pool-1-thread-2 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-2 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() 结束所有已提交任务并终止线程池。

        再修改WorkerPool.java,将工作队列大小设为3,如下所示:

//creating the ThreadPoolExecutor
ThreadPoolExecutor executorPool = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3), threadFactory, rejectionHandler);

        运行结果如下:

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

        在初始化 ThreadPoolExecutor 时,初始线程池大小设为2、最大值设为4、工作队列大小设为3。所以,如果当前有4个任务正在运行,而此时又有新任务提交,工作队列将只存储3个任务,其他任务将交由RejectedExecutionHandlerImpl 处理。

        进一步查看ThreadPoolExecutor的此构造方法源代码如下:

/**
 * Creates a new {@code ThreadPoolExecutor} with the given initial
 * parameters.
 *
 * @param corePoolSize the number of threads to keep in the pool, even
 *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
 * @param maximumPoolSize the maximum number of threads to allow in the
 *        pool
 * @param keepAliveTime when the number of threads is greater than
 *        the core, this is the maximum time that excess idle threads
 *        will wait for new tasks before terminating.
 * @param unit the time unit for the {@code keepAliveTime} argument
 * @param workQueue the queue to use for holding tasks before they are
 *        executed.  This queue will hold only the {@code Runnable}
 *        tasks submitted by the {@code execute} method.
 * @param threadFactory the factory to use when the executor
 *        creates a new thread
 * @param handler the handler to use when execution is blocked
 *        because the thread bounds and queue capacities are reached
 * @throws IllegalArgumentException if one of the following holds:<br>
 *         {@code corePoolSize < 0}<br>
 *         {@code keepAliveTime < 0}<br>
 *         {@code maximumPoolSize <= 0}<br>
 *         {@code maximumPoolSize < corePoolSize}
 * @throws NullPointerException if {@code workQueue}
 *         or {@code threadFactory} or {@code handler} is null
 */
public ThreadPoolExecutor(int corePoolSize,
						  int maximumPoolSize,
						  long keepAliveTime,
						  TimeUnit unit,
						  BlockingQueue<Runnable> workQueue,
						  ThreadFactory threadFactory,
						  RejectedExecutionHandler handler) {
	if (corePoolSize < 0 ||
		maximumPoolSize <= 0 ||
		maximumPoolSize < corePoolSize ||
		keepAliveTime < 0)
		throw new IllegalArgumentException();
	if (workQueue == null || threadFactory == null || handler == null)
		throw new NullPointerException();
	this.corePoolSize = corePoolSize;
	this.maximumPoolSize = maximumPoolSize;
	this.workQueue = workQueue;
	this.keepAliveTime = unit.toNanos(keepAliveTime);
	this.threadFactory = threadFactory;
	this.handler = handler;
}

        如果希望延迟执行或定期运行任务,那么可以使用 ScheduledThreadPoolExecutor 类。要了解更多,请参见 Java Schedule Thread Pool Executor

 

文章来源:http://www.importnew.com/8542.html

分享到:
评论

相关推荐

    java 线程池管理类:Executors_.docx

    `java.util.concurrent.Executors` 继承自 `java.lang.Object`,作为一个工具类,它提供了一系列用于创建和管理线程池的方法,包括`ExecutorService`、`ScheduledExecutorService`、`ThreadFactory`和`Callable`等...

    java 四种线程池实例

    本文将深入探讨四种常见的Java线程池实例:`ThreadPoolExecutor`、`Executors`提供的固定线程池、单线程池和定时线程池。 1. **ThreadPoolExecutor**: 这是最基础也是最灵活的线程池实现,可以通过`new ...

    java线程池实例

    本实例将深入探讨如何在Java中使用线程池,以及其背后的原理和最佳实践。 首先,线程池的基本工作原理是接收`Runnable`或`Callable`任务,将其存储在队列中,并由池中的线程处理。线程池可以预先配置最大线程数、...

    Java线程池使用说明

    5. Executors:包含了一系列静态工厂方法,用于生成不同类型的线程池实例。 常见的线程池实现包括: 1. newSingleThreadExecutor():创建一个单线程的线程池,保证任务按提交顺序串行执行。 2. ...

    java简单实现多线程及线程池实例详解

    java爬虫使用线程池实例可以有效地提高爬虫的执行效率和性能。下面是一个简单的示例: ```java public class threadPool { public static HashMap, Spiders&gt; statusMap = new HashMap, Spiders&gt;(); static ...

    线程池的使用介绍Demo,简单明了。

    线程池在Android开发中是不可或缺的一部分,尤其是在处理耗时操作如网络请求、数据库操作时,合理使用线程池能有效提升应用性能和用户体验。本文将通过一个简单的Demo,介绍如何在Android中使用线程池。 一、线程池...

    Android线程池管理的代码例子

    本示例将详细介绍如何在Android中使用两种主要的线程池:ThreadPoolExecutor和ScheduledExecutorService。 ThreadPoolExecutor是Java并发库中提供的一个基础线程池实现,它允许开发者自定义核心线程数、最大线程数...

    Spring boot注解@Async线程池实例详解

    Spring Boot @Async 注解线程池实例详解 1. Spring Boot @Async 注解简介 Spring Boot 提供了 @Async 注解,可以将方法异步化,使得方法的调用者不需要等待方法的执行结果,直接返回,而方法的实际执行将提交给 ...

    jdk自带线程池实例详解

    jdk自带线程池实例详解 jdk自带的线程池是Java开发中一个非常重要的概念,特别是在多线程编程中。线程池是线程的容器,每次只执行额定数量的线程,线程池就是用来管理这些额定数量的线程。下面我们来详细了解jdk...

    JAVA使用线程池查询大批量数据

    1. **创建线程池**:首先,我们需要创建一个线程池实例。通常,我们可以根据实际需求设置线程池参数。例如,如果数据量大且系统资源充足,可以适当增加线程数量;反之,若系统资源有限,应控制线程数量,避免资源...

    java线程池的使用方式

    为了简化线程池的配置和使用,`Executors`类提供了一系列静态工厂方法来创建常用的线程池。 - **newSingleThreadExecutor**:创建一个只包含一个线程的线程池。适用于需要保证任务顺序执行的场景,例如执行一系列...

    线程池代码

    - 避免使用`Executors`静态工厂方法创建线程池,因为它们创建的线程池可能无法满足复杂应用的需求,建议直接实例化`ThreadPoolExecutor`。 - 注意任务的粒度,太小的任务可能会导致线程创建和销毁的开销过大,而太...

    JAVA经典线程池源码

    - 使用`Executors`工厂类创建线程池,如`newFixedThreadPool`创建固定大小的线程池,`newCachedThreadPool`创建缓存线程池等。 - 提交任务到线程池,通过`ExecutorService`的`execute`方法将`Runnable`或`Callable...

    Java四种线程池的使用共6页.pdf.zip

    使用线程池时,我们通常会通过`Executors`工厂类创建实例,如`Executors.newFixedThreadPool(int nThreads)`。但需要注意的是,`Executors`类提供的静态方法在某些场景下可能会导致资源泄漏,因此推荐直接使用`...

    java线程和线程池的使用.docx

    Java 提供了 `java.util.concurrent` 包中的 `ExecutorService` 和 `ThreadPoolExecutor` 来管理线程池。线程池能有效控制运行的线程数量,避免因大量创建和销毁线程导致的性能开销。 创建线程池的基本步骤如下: ...

    java线程池使用说明[借鉴].pdf

    线程池的引入始于JDK 1.5,它引入了`java.util.concurrent`包,提供了`Executor`、`ExecutorService`和相关的实现类,如`ThreadPoolExecutor`和`ScheduledThreadPoolExecutor`。 线程池的主要作用是限制系统中同时...

    Zz: java 线程池设计思想

    但需要注意的是,这些预定义的线程池可能并不完全满足所有场景需求,因此在性能要求较高的情况下,建议直接实例化`ThreadPoolExecutor`并自定义参数。 此外,正确管理和监控线程池也非常重要,包括定期查看线程池...

    Java线程池文档

    但在JDK 1.5及以上版本,推荐使用`ThreadPoolExecutor`,它是线程池的核心实现,提供了更丰富的功能和配置选项。 `ThreadPool`类的构造函数接收一个`poolSize`参数,表示线程池中工作线程的数量,然后创建相应数量...

    java socket线程池

    这个方法会返回一个ThreadPoolExecutor实例,该实例是通过一个工厂方法实现的,这个工厂方法会配置好线程池的各个参数。 ThreadPoolExecutor构造器的参数如下: - corePoolSize:核心线程数,即线程池中长期存在的...

Global site tag (gtag.js) - Google Analytics