Java多线程系列--“JUC线程池”03之 线程池原理

Posted Hermioner

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java多线程系列--“JUC线程池”03之 线程池原理相关的知识,希望对你有一定的参考价值。

 

概要

在前面一章"Java多线程系列--“JUC线程池”02之 线程池原理(一)"中介绍了线程池的数据结构,本章会通过分析线程池的源码,对线程池进行说明。内容包括:

  • 线程池示例
  • 参考代码(基于JDK1.7.0_40)
  • 线程池源码分析
  •     (一) 创建“线程池”
  •     (二) 添加任务到“线程池”
  •     (三) 关闭“线程池”

线程池示例

在分析线程池之前,先看一个简单的线程池示例。

import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;

public class ThreadPoolDemo1 {

    public static void main(String[] args) {
        // 创建一个可重用固定线程数的线程池
        ExecutorService pool = Executors.newFixedThreadPool(2);
        // 创建实现了Runnable接口对象,Thread对象当然也实现了Runnable接口
        Thread ta = new MyThread();
        Thread tb = new MyThread();
        Thread tc = new MyThread();
        Thread td = new MyThread();
        Thread te = new MyThread();
        // 将线程放入池中进行执行
        pool.execute(ta);
        pool.execute(tb);
        pool.execute(tc);
        pool.execute(td);
        pool.execute(te);
        // 关闭线程池
        pool.shutdown();
    }
}

class MyThread extends Thread {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+ " is running.");
    }
}

运行结果

pool-1-thread-1 is running.
pool-1-thread-2 is running.
pool-1-thread-1 is running.
pool-1-thread-2 is running.
pool-1-thread-1 is running.

示例中,包括了线程池的创建,将任务添加到线程池中,关闭线程池这3个主要的步骤。稍后,我们会从这3个方面来分析ThreadPoolExecutor。

 

参考代码(基于JDK1.7.0_40)

Executors完整源码

  1 /*
  2  * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  3  *
  4  *
  5  *
  6  *
  7  *
  8  *
  9  *
 10  *
 11  *
 12  *
 13  *
 14  *
 15  *
 16  *
 17  *
 18  *
 19  *
 20  *
 21  *
 22  *
 23  */
 24 
 25 /*
 26  *
 27  *
 28  *
 29  *
 30  *
 31  * Written by Doug Lea with assistance from members of JCP JSR-166
 32  * Expert Group and released to the public domain, as explained at
 33  * http://creativecommons.org/publicdomain/zero/1.0/
 34  */
 35 
 36 package java.util.concurrent;
 37 import java.util.*;
 38 import java.util.concurrent.atomic.AtomicInteger;
 39 import java.security.AccessControlContext;
 40 import java.security.AccessController;
 41 import java.security.PrivilegedAction;
 42 import java.security.PrivilegedExceptionAction;
 43 import java.security.PrivilegedActionException;
 44 import java.security.AccessControlException;
 45 import sun.security.util.SecurityConstants;
 46 
 47 /**
 48  * Factory and utility methods for {@link Executor}, {@link
 49  * ExecutorService}, {@link ScheduledExecutorService}, {@link
 50  * ThreadFactory}, and {@link Callable} classes defined in this
 51  * package. This class supports the following kinds of methods:
 52  *
 53  * <ul>
 54  *   <li> Methods that create and return an {@link ExecutorService}
 55  *        set up with commonly useful configuration settings.
 56  *   <li> Methods that create and return a {@link ScheduledExecutorService}
 57  *        set up with commonly useful configuration settings.
 58  *   <li> Methods that create and return a "wrapped" ExecutorService, that
 59  *        disables reconfiguration by making implementation-specific methods
 60  *        inaccessible.
 61  *   <li> Methods that create and return a {@link ThreadFactory}
 62  *        that sets newly created threads to a known state.
 63  *   <li> Methods that create and return a {@link Callable}
 64  *        out of other closure-like forms, so they can be used
 65  *        in execution methods requiring <tt>Callable</tt>.
 66  * </ul>
 67  *
 68  * @since 1.5
 69  * @author Doug Lea
 70  */
 71 public class Executors {
 72 
 73     /**
 74      * Creates a thread pool that reuses a fixed number of threads
 75      * operating off a shared unbounded queue.  At any point, at most
 76      * <tt>nThreads</tt> threads will be active processing tasks.
 77      * If additional tasks are submitted when all threads are active,
 78      * they will wait in the queue until a thread is available.
 79      * If any thread terminates due to a failure during execution
 80      * prior to shutdown, a new one will take its place if needed to
 81      * execute subsequent tasks.  The threads in the pool will exist
 82      * until it is explicitly {@link ExecutorService#shutdown shutdown}.
 83      *
 84      * @param nThreads the number of threads in the pool
 85      * @return the newly created thread pool
 86      * @throws IllegalArgumentException if {@code nThreads <= 0}
 87      */
 88     public static ExecutorService newFixedThreadPool(int nThreads) {
 89         return new ThreadPoolExecutor(nThreads, nThreads,
 90                                       0L, TimeUnit.MILLISECONDS,
 91                                       new LinkedBlockingQueue<Runnable>());
 92     }
 93 
 94     /**
 95      * Creates a thread pool that reuses a fixed number of threads
 96      * operating off a shared unbounded queue, using the provided
 97      * ThreadFactory to create new threads when needed.  At any point,
 98      * at most <tt>nThreads</tt> threads will be active processing
 99      * tasks.  If additional tasks are submitted when all threads are
100      * active, they will wait in the queue until a thread is
101      * available.  If any thread terminates due to a failure during
102      * execution prior to shutdown, a new one will take its place if
103      * needed to execute subsequent tasks.  The threads in the pool will
104      * exist until it is explicitly {@link ExecutorService#shutdown
105      * shutdown}.
106      *
107      * @param nThreads the number of threads in the pool
108      * @param threadFactory the factory to use when creating new threads
109      * @return the newly created thread pool
110      * @throws NullPointerException if threadFactory is null
111      * @throws IllegalArgumentException if {@code nThreads <= 0}
112      */
113     public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
114         return new ThreadPoolExecutor(nThreads, nThreads,
115                                       0L, TimeUnit.MILLISECONDS,
116                                       new LinkedBlockingQueue<Runnable>(),
117                                       threadFactory);
118     }
119 
120     /**
121      * Creates an Executor that uses a single worker thread operating
122      * off an unbounded queue. (Note however that if this single
123      * thread terminates due to a failure during execution prior to
124      * shutdown, a new one will take its place if needed to execute
125      * subsequent tasks.)  Tasks are guaranteed to execute
126      * sequentially, and no more than one task will be active at any
127      * given time. Unlike the otherwise equivalent
128      * <tt>newFixedThreadPool(1)</tt> the returned executor is
129      * guaranteed not to be reconfigurable to use additional threads.
130      *
131      * @return the newly created single-threaded Executor
132      */
133     public static ExecutorService newSingleThreadExecutor() {
134         return new FinalizableDelegatedExecutorService
135             (new ThreadPoolExecutor(1, 1,
136                                     0L, TimeUnit.MILLISECONDS,
137                                     new LinkedBlockingQueue<Runnable>()));
138     }
139 
140     /**
141      * Creates an Executor that uses a single worker thread operating
142      * off an unbounded queue, and uses the provided ThreadFactory to
143      * create a new thread when needed. Unlike the otherwise
144      * equivalent <tt>newFixedThreadPool(1, threadFactory)</tt> the
145      * returned executor is guaranteed not to be reconfigurable to use
146      * additional threads.
147      *
148      * @param threadFactory the factory to use when creating new
149      * threads
150      *
151      * @return the newly created single-threaded Executor
152      * @throws NullPointerException if threadFactory is null
153      */
154     public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
155         return new FinalizableDelegatedExecutorService
156             (new ThreadPoolExecutor(1, 1,
157                                     0L, TimeUnit.MILLISECONDS,
158                                     new LinkedBlockingQueue<Runnable>(),
159                                     threadFactory));
160     }
161 
162     /**
163      * Creates a thread pool that creates new threads as needed, but
164      * will reuse previously constructed threads when they are
165      * available.  These pools will typically improve the performance
166      * of programs that execute many short-lived asynchronous tasks.
167      * Calls to <tt>execute</tt> will reuse previously constructed
168      * threads if available. If no existing thread is available, a new
169      * thread will be created and added to the pool. Threads that have
170      * not been used for sixty seconds are terminated and removed from
171      * the cache. Thus, a pool that remains idle for long enough will
172      * not consume any resources. Note that pools with similar
173      * properties but different details (for example, timeout parameters)
174      * may be created using {@link ThreadPoolExecutor} constructors.
175      *
176      * @return the newly created thread pool
177      */
178     public static ExecutorService newCachedThreadPool() {
179         return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
180                                       60L, TimeUnit.SECONDS,
181                                       new SynchronousQueue<Runnable>());
182     }
183 
184     /**
185      * Creates a thread pool that creates new threads as needed, but
186      * will reuse previously constructed threads when they are
187      * available, and uses the provided
188      * ThreadFactory to create new threads when needed.
189      * @param threadFactory the factory to use when creating new threads
190      * @return the newly created thread pool
191      * @throws NullPointerException if threadFactory is null
192      */
193     public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
194         return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
195                                       60L, TimeUnit.SECONDS,
196                                       new SynchronousQueue<Runnable>(),
197                                       threadFactory);
198     }
199 
200     /**
201      * Creates a single-threaded executor that can schedule commands
202      * to run after a given delay, or to execute periodically.
203      * (Note however that if this single
204      * thread terminates due to a failure during execution prior to
205      * shutdown, a new one will take its place if needed to execute
206      * subsequent tasks.)  Tasks are guaranteed to execute
207      * sequentially, and no more than one task will be active at any
208      * given time. Unlike the otherwise equivalent
209      * <tt>newScheduledThreadPool(1)</tt> the returned executor is
210      * guaranteed not to be reconfigurable to use additional threads.
211      * @return the newly created scheduled executor
212      */
213     public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
214         return new DelegatedScheduledExecutorService
215             (new ScheduledThreadPoolExecutor(1));
216     }
217 
218     /**
219      * Creates a single-threaded executor that can schedule commands
220      * to run after a given delay, or to execute periodically.  (Note
221      * however that if this single thread terminates due to a failure
222      * during execution prior to shutdown, a new one will take its
223      * place if needed to execute subsequent tasks.)  Tasks are
224      * guaranteed to execute sequentially, and no more than one task
225      * will be active at any given time. Unlike the otherwise
226      * equivalent <tt>newScheduledThreadPool(1, threadFactory)</tt>
227      * the returned executor is guaranteed not to be reconfigurable to
228      * use additional threads.
229      * @param threadFactory the factory to use when creating new
230      * threads
231      * @return a newly created scheduled executor
232      * @throws NullPointerException if threadFactory is null
233      */
234     public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {
235         return new DelegatedScheduledExecutorService
236             (new ScheduledThreadPoolExecutor(1, threadFactory));
237     }
238 
239     /**
240      * Creates a thread pool that can schedule commands to run after a
241      * given delay, or to execute periodically.
242      * @param corePoolSize the number of threads to keep in the pool,
243      * even if they are idle.
244      * @return a newly created scheduled thread pool
245      * @throws IllegalArgumentException if {@code corePoolSize < 0}
246      */
247     public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
248         return new ScheduledThreadPoolExecutor(corePoolSize);
249     }
250 
251     /**
252      * Creates a thread pool that can schedule commands to run after a
253      * given delay, or to execute periodically.
254      * @param corePoolSize the number of threads to keep in the pool,
255      * even if they are idle.
256      * @param threadFactory the factory to use when the executor
257      * creates a new thread.
258      * @return a newly created scheduled thread pool
259      * @throws IllegalArgumentException if {@code corePoolSize < 0}
260      * @throws NullPointerException if threadFactory is null
261      */
262     public static ScheduledExecutorService newScheduledThreadPool(
263             int corePoolSize, ThreadFactory threadFactory) {
264         return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
265     }
266 
267 
268     /**
269      * Returns an object that delegates all defined {@link
270      * ExecutorService} methods to the given executor, but not any
271      * other methods that might otherwise be accessible using
272      * casts. This provides a way to safely "freeze" configuration and
273      * disallow tuning of a given concrete implementation.
274      * @param executor the underlying implementation
275      * @return an <tt>ExecutorService</tt> instance
276      * @throws NullPointerException if executor null
277      */
278     public static ExecutorService unconfigurableExecutorService(ExecutorService executor) {
279         if (executor == null)
280             throw new NullPointerException();
281         return new DelegatedExecutorService(executor);
282     }
283 
284     /**
285      * Returns an object that delegates all defined {@link
286      * ScheduledExecutorService} methods to the given executor, but
287      * not any other methods that might otherwise be accessible using
288      * casts. This provides a way to safely "freeze" configuration and
289      * disallow tuning of a given concrete implementation.
290      * @param executor the underlying implementation
291      * @return a <tt>ScheduledExecutorService</tt> instance
292      * @throws NullPointerException if executor null
293      */
294     public static ScheduledExecutorService unconfigurableScheduledExecutorService(ScheduledExecutorService executor) {
295         if (executor == null)
296             throw new NullPointerException();
297         return new DelegatedScheduledExecutorService(executor);
298     }
299 
300     /**
301      * Returns a default thread factory used to create new threads.
302      * This factory creates all new threads used by an Executor in the
303      * same {@link ThreadGroup}. If there is a {@link
304      * java.lang.SecurityManager}, it uses the group of {@link
305      * System#getSecurityManager}, else the group of the thread
306      * invoking this <tt>defaultThreadFactory</tt> method. Each new
307      * thread is created as a non-daemon thread with priority set to
308      * the smaller of <tt>Thread.NORM_PRIORITY</tt> and the maximum
309      * priority permitted in the thread group.  New threads have names
310      * accessible via {@link Thread#getName} of
311      * <em>pool-N-thread-M</em>, where <em>N</em> is the sequence
312      * number of this factory, and <em>M</em> is the sequence number
313      * of the thread created by this factory.
314      * @return a thread factory
315      */
316     public static ThreadFactory defaultThreadFactory() {
317         return new DefaultThreadFactory();
318     }
319 
320     /**
321      * Returns a thread factory used to create new threads that
322      * have the same permissions as the current thread.
323      * This factory creates threads with the same settings as {@link
324      * Executors#defaultThreadFactory}, additionally setting the
325      * AccessControlContext and contextClassLoader of new threads to
326      * be the same as the thread invoking this
327      * <tt>privilegedThreadFactory</tt> method.  A new
328      * <tt>privilegedThreadFactory</tt> can be created within an
329      * {@link AccessController#doPrivileged} action setting the
330      * current thread\'s access control context to create threads with
331      * the selected permission settings holding within that action.
332      *
333      * <p> Note that while tasks running within such threads will have
334      * the same access control and class loader settings as the
335      * current thread, they need not have the same {@link
336      * java.lang.ThreadLocal} or {@link
337      * java.lang.InheritableThreadLocal} values. If necessary,
338      * particular values of thread locals can be set or reset before
339      * any task runs in {@link ThreadPoolExecutor} subclasses using
340      * {@link ThreadPoolExecutor#beforeExecute}. Also, if it is
341      * necessary to initialize worker threads to have the same
342      * InheritableThreadLocal settings as some other designated
343      * thread, you can create a custom ThreadFactory in which that
344      * thread waits for and services requests to create others that
345      * will inherit its values.
346      *
347      * @return a thread factory
348      * @throws AccessControlException if the current access control
349      * context does not have permission to both get and set context
350      * class loader.
351      */
352     public static ThreadFactory privilegedThreadFactory() {
353         return new PrivilegedThreadFactory();
354<

以上是关于Java多线程系列--“JUC线程池”03之 线程池原理的主要内容,如果未能解决你的问题,请参考以下文章

java多线程系类:JUC线程池:03之线程池原理(转)

Java多线程系列--“JUC线程池”01之 线程池架构

Java多线程系列--“JUC线程池”02之 线程池原理

Java多线程系列--“JUC线程池”02之 线程池原理

Java多线程系列--“JUC线程池”04之 线程池原理

Java多线程系列--“JUC线程池”04之 线程池原理