首页 技术 正文
技术 2022年11月21日
0 收藏 448 点赞 3,594 浏览 11008 个字

对javaSE中JDK提供的四种线程池稍作整理 一、Executor package java.util.concurrent;/*** @since 1.5* @author Doug Lea*/public interface Executor {/*** Executes the given command at some time in the future. The command* may execute in a new thread, in a pooled thread, or in the calling* thread, at the discretion of the {@code Executor} implementation.** @param command the runnable task* @throws RejectedExecutionException if this task cannot be* accepted for execution* @throws NullPointerException if command is null*/ void execute(Runnable command);} 二、Runnable package java.lang;/*** The <code>Runnable</code> interface should be implemented by any* class whose instances are intended to be executed by a thread. The* class must define a method of no arguments called <code>run</code>.* <p>* This interface is designed to provide a common protocol for objects that* wish to execute code while they are active. For example,* <code>Runnable</code> is implemented by class <code>Thread</code>.* Being active simply means that a thread has been started and has not* yet been stopped.* <p>* In addition, <code>Runnable</code> provides the means for a class to be* active while not subclassing <code>Thread</code>. A class that implements* <code>Runnable</code> can run without subclassing <code>Thread</code>* by instantiating a <code>Thread</code> instance and passing itself in* as the target. In most cases, the <code>Runnable</code> interface should* be used if you are only planning to override the <code>run()</code>* method and no other <code>Thread</code> methods.* This is important because classes should not be subclassed* unless the programmer intends on modifying or enhancing the fundamental* behavior of the class.** @author Arthur van Hoff* @see java.lang.Thread* @see java.util.concurrent.Callable* @since JDK1.0*/@FunctionalInterface // 函数式接口,只能有一个自定义方法,可以有继承Object的方法public interface Runnable {/*** When an object implementing interface <code>Runnable</code> is used* to create a thread, starting the thread causes the object’s* <code>run</code> method to be called in that separately executing* thread.* <p>* The general contract of the method <code>run</code> is that it may* take any action whatsoever.** @see java.lang.Thread#run()*/ public abstract void run();} 三、线程池工厂类 Executors package java.util.concurrent;import java.util.*;import java.util.concurrent.atomic.AtomicInteger;import java.security.AccessControlContext;import java.security.AccessController;import java.security.PrivilegedAction;import java.security.PrivilegedExceptionAction;import java.security.PrivilegedActionException;import java.security.AccessControlException;import sun.security.util.SecurityConstants; /*** Exectors提供了工厂方法和可用的方法为: Executor、ExecutorService, * ScheduledExecutorService,ThreadFactory,Callable。* Factory and utility methods for {@link Executor}, {@link* ExecutorService}, {@link ScheduledExecutorService}, {@link* ThreadFactory}, and {@link Callable} classes defined in this* package. This class supports the following kinds of methods:* 还提供以下的方法:** [list]* <li> Methods that create and return an {@link ExecutorService}* set up with commonly useful configuration settings.根据通用配置参数,创建并返回一个ExecutorService** <li> Methods that create and return a {@link ScheduledExecutorService}* set up with commonly useful configuration settings.根据通用的配置参数,创建并返回一个ScheduledExecutorService** <li> Methods that create and return a “wrapped” ExecutorService, that* disables reconfiguration by making implementation-specific methods* inaccessible.创建并返回一个包装的ExecutorService,不能重新配置** <li> Methods that create and return a {@link ThreadFactory}* that sets newly created threads to a known state.创建并返回一个ThreadFactory,设置创建线程为指定状态** <li> Methods that create and return a {@link Callable}* out of other closure-like forms, so they can be used* in execution methods requiring {@code Callable}.创建并返回一个闭包形式的Callable,以便可以在执行方法中执行需要的形式的Callable。* [/list]** @since 1.5* @author Doug Lea*/ public class Executors {/*** Creates a thread pool that reuses a fixed number of threads* operating off a shared unbounded queue. At any point, at most* {@code nThreads} threads will be active processing tasks.* they will wait in the queue until a thread is available.* If any thread terminates due to a failure during execution* prior to shutdown, a new one will take its place if needed to* execute subsequent tasks. The threads in the pool will exist* until it is explicitly {@link ExecutorService#shutdown shutdown}.*创建一个可以重用的固定数量n的工作线程和无界的共享队列的线程池。在任何时候,最多有 nThreads个工作线程。如果所有的工作线程都在执行任务,有新提交的任务将会在任务队列中等待,直到有工作线程可以利用。如果有任何线程在终止之前执行任务失败,有需要的话,一个新的工作线程会代替它执行任务。直到线程池关闭,线程池中的工作线程才会退出。 * @param nThreads the number of threads in the pool* @return the newly created thread pool* @throws IllegalArgumentException if {@code nThreads <= 0}*/ public static ExecutorService newFixedThreadPool(int nThreads) {  return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } /*** @param nThreads the number of threads in the pool* @param threadFactory the factory to use when creating new threads* @return the newly created thread pool* @throws NullPointerException if threadFactory is null* @throws IllegalArgumentException if {@code nThreads <= 0}*/// 与以上方法比较是增加了线程池参数ThreadFactory public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {  return new ThreadPoolExecutor( nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); }  /*** Creates an Executor that uses a single worker thread operating* off an unbounded queue. (Note however that if this single* thread terminates due to a failure during execution prior to* shutdown, a new one will take its place if needed to execute* subsequent tasks.) Tasks are guaranteed to execute* sequentially, and no more than one task will be active at any* given time. Unlike the otherwise equivalent* {@code newFixedThreadPool(1)} the returned executor is* guaranteed not to be reconfigurable to use additional threads.*创建工作线程与无界队列的执行器(如果工作线程在线程池关闭之前,执行任务的过程, 工作线程由于失败结束,则一个新工作线程将会创建,替代旧的工作线程)。保证任务相继被执行,而且任何时间都只有一个线程。和newFixedThreadPool(1)不同,返回的Executor保证不会重构额外的线程。相当于不能使用setCorePoolSize这些方法。 * @return the newly created single-threaded Executor*/ public static ExecutorService newSingleThreadExecutor() {  return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }  /*** Creates an Executor that uses a single worker thread operating* off an unbounded queue, and uses the provided ThreadFactory to* create a new thread when needed. Unlike the otherwise* equivalent {@code newFixedThreadPool(1, threadFactory)} the* returned executor is guaranteed not to be reconfigurable to use* additional threads.** @param threadFactory the factory to use when creating new* threads** @return the newly created single-threaded Executor* @throws NullPointerException if threadFactory is null*/// 创建单线程执行器,与前一个方法的不同为,添加了线程工厂参数ThreadFactory public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) { return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(),threadFactory)); } 从上面来看Executors创建固定线程池,实际为ThreadPoolExecutor,核心线程池数量和最大线程池数量相等并且固定,任务队 列为LinkedBlockingQueue;创建单线程执行器,通过单线程执行器代理,实际为线程池执行器的ThreadPoolExecutor静态代理,核心线程池数量和最大线程池数量相等并且为1,任务队列为LinkedBlockingQueue。 /*** Creates a thread pool that creates new threads as needed, but* will reuse previously constructed threads when they are* available. These pools will typically improve the performance* of programs that execute many short-lived asynchronous tasks.* Calls to {@code execute} will reuse previously constructed* threads if available. If no existing thread is available, a new* thread will be created and added to the pool. Threads that have* not been used for sixty seconds are terminated and removed from* the cache. Thus, a pool that remains idle for long enough will* not consume any resources. Note that pools with similar* properties but different details (for example, timeout parameters)* may be created using {@link ThreadPoolExecutor} constructors.*创建一个可根据需要创建工作线程的线程池,如果有空闲可用的工作线程就重用。这个线程池可以明显改善执行大量执行时间段的异步任务场景的性能。当调用execute方法时,会重用空闲工作线程。如果没有可利用的工作线程,则将创建新的线程并添加到线程池中。如果线程池中的工作线程在60s内没有执行任务将会被移除。这样工作线程的空闲等待时间足够,也不会浪费太多资源。 * @return the newly created thread pool*/ public static ExecutorService newCachedThreadPool() {  return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>()); } /*** Creates a thread pool that creates new threads as needed, but* will reuse previously constructed threads when they are* available, and uses the provided* ThreadFactory to create new threads when needed.* @param threadFactory the factory to use when creating new threads* @return the newly created thread pool* @throws NullPointerException if threadFactory is null*/// 有线程工厂ThreadFactory参数的newCachedThreadPool方法public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>(),threadFactory);} 从newCachedThreadPool方法来看,核心线程池为0,最大线程池为Integer.MAX_VALUE,工作线程可空闲时间为60秒,任务队列为SynchronousQueue。newCachedThreadPool方法创建的线程适合需要执行大量执行时间短的异步任务场景。 /*** Creates a single-threaded executor that can schedule commands* to run after a given delay, or to execute periodically.* (Note however that if this single* thread terminates due to a failure during execution prior to* shutdown, a new one will take its place if needed to execute* subsequent tasks.) Tasks are guaranteed to execute* sequentially, and no more than one task will be active at any* given time. Unlike the otherwise equivalent* {@code newScheduledThreadPool(1)} the returned executor is* guaranteed not to be reconfigurable to use additional threads. 创建一个可以执行延时的任务和间歇性的任务单线程执行器如果工作线程在线程池关闭之前,执行任务的过程, 工作线程由于失败结束,则一个新工作线程将会创建,替代旧的工作线程)。保证任务按顺序执行,在任何时候不会有两个任务同时执行。 * @return the newly created scheduled executor*/ public static ScheduledExecutorService newSingleThreadScheduledExecutor() {// 返回调度执行器代理 return new DelegatedScheduledExecutorService(new ScheduledThreadPoolExecutor(1));} /*** Creates a single-threaded executor that can schedule commands* to run after a given delay, or to execute periodically. (Note* however that if this single thread terminates due to a failure* during execution prior to shutdown, a new one will take its* place if needed to execute subsequent tasks.) Tasks are* guaranteed to execute sequentially, and no more than one task* will be active at any given time. Unlike the otherwise* equivalent {@code newScheduledThreadPool(1, threadFactory)}* the returned executor is guaranteed not to be reconfigurable to* use additional threads.* @param threadFactory the factory to use when creating new* threads* @return a newly created scheduled executor* @throws NullPointerException if threadFactory is null*/// 此方与上一个方法的不同为,有线程工厂参数public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {return new DelegatedScheduledExecutorService(new ScheduledThreadPoolExecutor(1, threadFactory));}从上面来看单线程调度器实际为调度执行器静态代理,实际的调度执行器为ScheduledThreadPoolExecutor。 /*** Creates a thread pool that can schedule commands to run after a* given delay, or to execute periodically.* @param corePoolSize the number of threads to keep in the pool,* even if they are idle* @return a newly created scheduled thread pool* @throws IllegalArgumentException if {@code corePoolSize < 0}*/public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {return new ScheduledThreadPoolExecutor(corePoolSize);} /*** Creates a thread pool that can schedule commands to run after a* given delay, or to execute periodically.* @param corePoolSize the number of threads to keep in the pool,* even if they are idle* @param threadFactory the factory to use when the executor* creates a new thread* @return a newly created scheduled thread pool* @throws IllegalArgumentException if {@code corePoolSize < 0}* @throws NullPointerException if threadFactory is null*/public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) {return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);}  }

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,965
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,486
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,331
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,114
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,747
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,781