Executor实现类--ThreadPoolExecutor

来源:互联网 发布:单片机数据总线 编辑:程序博客网 时间:2024/06/08 15:15

• Junior programmers think concurrency is hard.
• Experienced programmers think concurrency is easy.
• Senior programmers think concurrency is hard.

初级程序员认为并发编程很难;

有经验的程序员认为并发编程很容易;

高级程序员认为并发编程很难。

不知道是不是这么一回事,反正对我来说难。


今天记录一个Executor的实现类ThreadPoolExecutor的实例。


ThreadPoolExecutor 保持一个线程池并且分发Runnable的实例到线程池中的execute()方法执行。

ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable>workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)

corePoolSize: 决定初始时线程池有多少个线程被启动,当队列满时才会启动新的线程。

maximumPoolSize: 线程池中启动的最大的线程数量,可以设置Integer.MAX_VALUE 让线程池的线程数量没有上限。

keepAliveTime: 当ThreadPoolExecutor实例创建超过corePoolSize数量的线程时,一个线程空闲多少时间后将被从线程池中移除。

unit: keepAliveTime的时间单位。

workQueue: 保持在execute()方法执行的Runnable实例的队列,到这个Runnable实例被启动。

threadFactory: 创建用于ThreadPoolExecutor的线程的接口的工厂实现类。

handler: 当你指定一个工作缓冲队列和一个线程池最大线程数量,有可能出现ThreadPoolExecutor实例因为饱和而无法处理的一些Runnable实例。在这种情况下,会调用提供的handler实例,使你能在发生这种情况时做一些处理。


ThreadPoolExecutorExample:

package club.younge.demo;import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.RejectedExecutionHandler;import java.util.concurrent.ThreadFactory;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;public class ThreadPoolExecutorExample implements Runnable {//本类为线程实现类private static AtomicInteger counter = new AtomicInteger();private final int taskId;public int getTaskId() {return taskId;}public ThreadPoolExecutorExample(int taskId) {this.taskId = taskId;}public void run() { //线程真正执行try {System.out.println("executor work thread " + taskId );Thread.sleep(5000);    //休眠5秒} catch (InterruptedException e) {e.printStackTrace();}}public static void main(String[] args) {BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(10);  //工作缓存队列ThreadFactory threadFactory = new ThreadFactory() {    //线程制造工厂,public Thread newThread(Runnable r) { //线程创建int currentCount = counter.getAndIncrement();System.out.println("Creating new thread: " + currentCount);return new Thread(r, "mythread" + currentCount);}};RejectedExecutionHandler rejectedHandler = new RejectedExecutionHandler() { //被拒的Runnable处理Handlerpublic void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {if (r instanceof ThreadPoolExecutorExample) {ThreadPoolExecutorExample example = (ThreadPoolExecutorExample) r;System.out.println("Rejecting task with id " + example.getTaskId());}}};ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 1, TimeUnit.SECONDS, queue, threadFactory, rejectedHandler);for (int i = 0; i < 100; i++) {executor.execute(new ThreadPoolExecutorExample(i));}executor.shutdown();
                //executor.shutdownNow();//正在休眠的10线程将被立即唤醒,跳入InterruptedException异常,并打印堆栈信息。}}


1 0
原创粉丝点击