JAVA多线程之扩展ThreadPoolExecutor

简介: ThreadPoolExecutor是可扩展的,通过查看源码可以发现,它提供了几个可以在子类化中改写的方法:beforeExecute,afterExecute,terminated.源码片段如下所示:protected void beforeExecute(Thread t, Runnable r) { }protected void afterExecute(Runnable r, Throwable t) { }protected void terminated() { }可以注意到,这三个方法都是protected的空方法,摆明了是让子类扩展的嘛。

ThreadPoolExecutor是可扩展的,通过查看源码可以发现,它提供了几个可以在子类化中改写的方法:beforeExecute,afterExecute,terminated.

源码片段如下所示:

protected void beforeExecute(Thread t, Runnable r) { }
protected void afterExecute(Runnable r, Throwable t) { }
protected void terminated() { }
可以注意到,这三个方法都是protected的空方法,摆明了是让子类扩展的嘛。

在执行任务的线程中将调用beforeExecute和afterExecute等方法,在这些方法中还可以添加日志、计时、监视或者统计信息收集的功能。无论任务是从run中正常返回,还是抛出一个异常而返回,afterExecute都会被调用。如果任务在完成后带有一个Error,那么就不会调用afterExecute。如果beforeExecute抛出一个RuntimeException,那么任务将不被执行,并且afterExecute也不会被调用。

在线程池完成关闭时调用terminated,也就是在所有任务都已经完成并且所有工作者线程也已经关闭后,terminated可以用来释放Executor在其生命周期里分配的各种资源,此外还可以执行发送通知、记录日志或者手机finalize统计等操作。

下面就以给线程池添加统计信息为例(添加日志和及时等功能):

package com.threadPool;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;

public class TimingThreadPool extends ThreadPoolExecutor
{
	private final ThreadLocal<Long> startTime = new ThreadLocal<Long>();
	private final Logger log = Logger.getAnonymousLogger();
	private final AtomicLong numTasks = new AtomicLong();
	private final AtomicLong totalTime = new AtomicLong();
	
	public TimingThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
			BlockingQueue<Runnable> workQueue)
	{
		super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
	}

	protected void beforeExecute(Thread t, Runnable r){
		super.beforeExecute(t, r);
		log.info(String.format("Thread %s: start %s", t,r));
		startTime.set(System.nanoTime());
	}
	
	protected void afterExecute(Runnable r, Throwable t){
		try{
			long endTime = System.nanoTime();
			long taskTime = endTime-startTime.get();
			numTasks.incrementAndGet();
			totalTime.addAndGet(taskTime);
			log.info(String.format("Thread %s: end %s, time=%dns", t,r,taskTime));
		}
		finally
		{
			super.afterExecute(r, t);
		}
	}
	
	protected void terminated()
	{
		try
		{
			log.info(String.format("Terminated: avg time=%dns",totalTime.get()/numTasks.get()));
		}
		finally
		{
			super.terminated();
		}
	}
}
可以看到TimingThreadPool重写了父类的三个方法。

下面写一个测试类,参考运行效果:

package com.threadPool;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class CheckTimingThreadPool
{
	public static void main(String[] args)
	{
		ThreadPoolExecutor  exec = new TimingThreadPool(0, Integer.MAX_VALUE,
                60L, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>());
		exec.execute(new DoSomething(5));
		exec.execute(new DoSomething(4));
		exec.execute(new DoSomething(3));
		exec.execute(new DoSomething(2));
		exec.execute(new DoSomething(1));
		exec.shutdown();
	}

}

class DoSomething implements Runnable{
	private int sleepTime;
	public DoSomething(int sleepTime)
	{
		this.sleepTime = sleepTime;
	}
	@Override
	public void run()
	{
		System.out.println(Thread.currentThread().getName()+" is running.");
		try
		{
			TimeUnit.SECONDS.sleep(sleepTime);
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
	}
	
}
运行结果:

十二月 25, 2015 4:18:42 下午 com.threadPool.TimingThreadPool beforeExecute
信息: Thread Thread[pool-1-thread-1,5,main]: start com.threadPool.DoSomething@43f459c2
十二月 25, 2015 4:18:42 下午 com.threadPool.TimingThreadPool beforeExecute
信息: Thread Thread[pool-1-thread-3,5,main]: start com.threadPool.DoSomething@33891d5d
pool-1-thread-3 is running.
十二月 25, 2015 4:18:42 下午 com.threadPool.TimingThreadPool beforeExecute
信息: Thread Thread[pool-1-thread-4,5,main]: start com.threadPool.DoSomething@33891d5d
pool-1-thread-4 is running.
十二月 25, 2015 4:18:42 下午 com.threadPool.TimingThreadPool beforeExecute
信息: Thread Thread[pool-1-thread-5,5,main]: start com.threadPool.DoSomething@10747b4
pool-1-thread-5 is running.
十二月 25, 2015 4:18:42 下午 com.threadPool.TimingThreadPool beforeExecute
信息: Thread Thread[pool-1-thread-2,5,main]: start com.threadPool.DoSomething@7d4af469
pool-1-thread-2 is running.
pool-1-thread-1 is running.
十二月 25, 2015 4:18:43 下午 com.threadPool.TimingThreadPool afterExecute
信息: Thread null: end com.threadPool.DoSomething@10747b4, time=999589906ns
十二月 25, 2015 4:18:44 下午 com.threadPool.TimingThreadPool afterExecute
信息: Thread null: end com.threadPool.DoSomething@33891d5d, time=1999461618ns
十二月 25, 2015 4:18:45 下午 com.threadPool.TimingThreadPool afterExecute
信息: Thread null: end com.threadPool.DoSomething@33891d5d, time=3000507593ns
十二月 25, 2015 4:18:46 下午 com.threadPool.TimingThreadPool afterExecute
信息: Thread null: end com.threadPool.DoSomething@7d4af469, time=3999691253ns
十二月 25, 2015 4:18:47 下午 com.threadPool.TimingThreadPool afterExecute
信息: Thread null: end com.threadPool.DoSomething@43f459c2, time=4999778490ns
十二月 25, 2015 4:18:47 下午 com.threadPool.TimingThreadPool terminated
信息: Terminated: avg time=2999805772ns
可以看到,在测试类CheckTimingThreadPool中通过execute了五个线程,然后分别对这五个线程进行统计,最后统计出各个线程的耗时平均时间。

这里说明下TimingThreadPool的构造函数,它直接调用了父类的构造方法,在ThreadPoolExecutor中有许多构造方法,有兴趣的朋友可以查看jdk api或者源码进行查看。

简要说明下构造函数的参数的含义:

corePoolSize:线程池维护线程的最少数量

maximumPoolSize:线程池维护线程的最大数量

keepAliveTime:线程池维护线程所允许的空闲时间

unit:线程池维护所允许的空闲时间的单位

workQueue:线程池所使用的缓存队列



目录
相关文章
|
2天前
|
安全 Java 调度
深入理解Java并发编程:线程安全与性能优化
【5月更文挑战第12天】 在现代软件开发中,多线程编程是提升应用程序性能和响应能力的关键手段之一。特别是在Java语言中,由于其内置的跨平台线程支持,开发者可以轻松地创建和管理线程。然而,随之而来的并发问题也不容小觑。本文将探讨Java并发编程的核心概念,包括线程安全策略、锁机制以及性能优化技巧。通过实例分析与性能比较,我们旨在为读者提供一套既确保线程安全又兼顾性能的编程指导。
|
1天前
|
Java
Java中的多线程编程:基础知识与实践
【5月更文挑战第13天】在计算机科学中,多线程是一种使得程序可以同时执行多个任务的技术。在Java语言中,多线程的实现主要依赖于java.lang.Thread类和java.lang.Runnable接口。本文将深入探讨Java中的多线程编程,包括其基本概念、实现方法以及一些常见的问题和解决方案。
|
1天前
|
安全 算法 Java
深入理解Java并发编程:线程安全与性能优化
【5月更文挑战第13天】 在Java开发中,并发编程是一个复杂且重要的领域。它不仅关系到程序的线程安全性,也直接影响到系统的性能表现。本文将探讨Java并发编程的核心概念,包括线程同步机制、锁优化技术以及如何平衡线程安全和性能。通过分析具体案例,我们将提供实用的编程技巧和最佳实践,帮助开发者在确保线程安全的同时,提升应用性能。
10 1
|
2天前
|
Java 调度
Java一分钟之线程池:ExecutorService与Future
【5月更文挑战第12天】Java并发编程中,`ExecutorService`和`Future`是关键组件,简化多线程并提供异步执行能力。`ExecutorService`是线程池接口,用于提交任务到线程池,如`ThreadPoolExecutor`和`ScheduledThreadPoolExecutor`。通过`submit()`提交任务并返回`Future`对象,可检查任务状态、获取结果或取消任务。注意处理`ExecutionException`和避免无限等待。实战示例展示了如何异步执行任务并获取结果。理解这些概念对提升并发性能至关重要。
17 5
|
3天前
|
Java
Java一分钟:线程协作:wait(), notify(), notifyAll()
【5月更文挑战第11天】本文介绍了Java多线程编程中的`wait()`, `notify()`, `notifyAll()`方法,它们用于线程间通信和同步。这些方法在`synchronized`代码块中使用,控制线程执行和资源访问。文章讨论了常见问题,如死锁、未捕获异常、同步使用错误及通知错误,并提供了生产者-消费者模型的示例代码,强调理解并正确使用这些方法对实现线程协作的重要性。
14 3
|
3天前
|
安全 算法 Java
Java一分钟:线程同步:synchronized关键字
【5月更文挑战第11天】Java中的`synchronized`关键字用于线程同步,防止竞态条件,确保数据一致性。本文介绍了其工作原理、常见问题及避免策略。同步方法和同步代码块是两种使用形式,需注意避免死锁、过度使用导致的性能影响以及理解锁的可重入性和升级降级机制。示例展示了同步方法和代码块的运用,以及如何避免死锁。正确使用`synchronized`是编写多线程安全代码的核心。
55 2
|
3天前
|
安全 Java 调度
Java一分钟:多线程编程初步:Thread类与Runnable接口
【5月更文挑战第11天】本文介绍了Java中创建线程的两种方式:继承Thread类和实现Runnable接口,并讨论了多线程编程中的常见问题,如资源浪费、线程安全、死锁和优先级问题,提出了解决策略。示例展示了线程通信的生产者-消费者模型,强调理解和掌握线程操作对编写高效并发程序的重要性。
43 3
|
3天前
|
安全 Java
深入理解Java并发编程:线程安全与性能优化
【5月更文挑战第11天】在Java并发编程中,线程安全和性能优化是两个重要的主题。本文将深入探讨这两个方面,包括线程安全的基本概念,如何实现线程安全,以及如何在保证线程安全的同时进行性能优化。我们将通过实例和代码片段来说明这些概念和技术。
4 0
|
3天前
|
Java 调度
Java并发编程:深入理解线程池
【5月更文挑战第11天】本文将深入探讨Java中的线程池,包括其基本概念、工作原理以及如何使用。我们将通过实例来解释线程池的优点,如提高性能和资源利用率,以及如何避免常见的并发问题。我们还将讨论Java中线程池的实现,包括Executor框架和ThreadPoolExecutor类,并展示如何创建和管理线程池。最后,我们将讨论线程池的一些高级特性,如任务调度、线程优先级和异常处理。
|
4天前
|
安全 Java
【JAVA进阶篇教学】第十篇:Java中线程安全、锁讲解
【JAVA进阶篇教学】第十篇:Java中线程安全、锁讲解