为了更好的控制多线程,JDK提供了一套线程框架Executors,帮助开发人员有效地进行线程控制。它们都在java.util.concurrent包中,是JDK并发包的核心。
Executors,他扮演这线程工厂的角色,我们通过Executors可以创建特定功能的线程池。
Executors创建线程池方法:
•newFixedThreadPool()方法:该方法返回一个固定数量的线程池,该方法的线程数始终不变,当有一个任务提交时,若线程池中空闲,则立即执行,若没有,则会被暂缓在一个任务队列中等待有空闲的线程去执行。
•newSingleThreadExecutor ()方法:创建一个线程的线程池,若空闲则执行,若没有空闲线程则暂缓在任务列队中。
•newCachedThreadPool()方法:返回一个可根据实际情况调整线程个数的线程池,不限制最大线程数量,若有任务,则创建线程,若无任务则不创建线程。如果没有任务则线程在60s后自动回收(空闲时间60s)。
•newScheduledThreadPool()方法:该方法返回一个SchededExecutorService对象,但该线程池可以指定线程的数量。
public class UseExecutors {
public static void main(String[] args) {
//1 创建固定数量的线程池
/* 底层实现:使用ThreadPoolExecutor来实现
* public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
*/
ExecutorService executorService1 = Executors.newFixedThreadPool(5);
//2 创建单线程的线程池
/* 底层实现
* public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService //此处保障一层作用在于内部定义了fanil属性,以免被改变
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
*/
ExecutorService executorService2 = Executors.newSingleThreadExecutor();
//3 创建一个没有容量限制的线程池
ExecutorService executorService3 = Executors.newCachedThreadPool();
//4 创建一个带有定时机制的线程池,区别于其他线程池在于可以传入定时任务
/* public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
* public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
//DelayedWorkQueue带有延迟执行的队列
}
ScheduledThreadPoolExecutor中的super就是ThreadPoolExecutor
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
本质上和其他的线程池没有任务区别都是使用ThreadPoolExecutor来创建,区别在于投递入队列的时候改变了,应用了
DelayedWorkQueue延迟队列。*/
ScheduledExecutorService executorService4 = Executors.newScheduledThreadPool(1);
//参数一需要传入一个带有Runnable接口的任务,参数二为初始化的延迟时间,参数三每次延迟时间间隔,参数四时间戳
executorService4.scheduleWithFixedDelay(new Take(1), 5, 2, TimeUnit.SECONDS);
}
}