要配置一个线程池是比较复杂的,尤其是对于线程池的原理不是很清楚的情况下,很有可能配置的线程池不是较优的,因此在Executors类里面提供了一些静态工厂,生成一些常用的线程池。
常用的线程池、Java 里面线程池的顶级接口是 Executor,但是严格意义上讲 Executor 并不是一个线程池,而只是一个执行线程的工具。真正的线程池接口是 ExecutorService。
Java通过Executors工厂类提供四种线程池,分别为:
Executors.newSingleThreadExecutor()返回一个线程池(这个线程池只有一个线程),这个线程池可以在线程死后(或发生异常时)重新启动一个线程来替代原来的线程继续执行下去!
代码实现
package cn.wideth.util;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;class MyRunnable implements Runnable {@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + " is running...");}}public class MyNewSingleThreadExecutor {public static void main(String[] args) {ExecutorService executorService = Executors.newSingleThreadExecutor();MyRunnable myRunnable = new MyRunnable();for (int i = 0; i < 10; i++) {executorService.execute(myRunnable);}System.out.println("线程任务开始执行");executorService.shutdown();}}
线程池的使用。运行结果:
底层实现
/*** 核心线程池大小=1* 最大线程池大小为1* 线程过期时间为0ms* LinkedBlockingQueue作为工作队列*/
public static ExecutorService newSingleThreadExecutor() {return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()));
}
从参数可以看出来,SingleThreadExecutor 相当于特殊的 FixedThreadPool,它的执行流程如下:
java多线程池、SingleThreadExecutor 用于串行执行任务的场景,每个任务必须按顺序执行,不需要并发执行。
创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。在任意点,在大多数 nThreads 线程会处于处理任务的活动状态。如果在所有线程处于活动状态时提交附加任务,则在有可用线程之前,附加任务将在队列中等待。如果在关闭前的执行期间由于失败而导致任何线程终止,那么一个新线程将代替它执行后续的任务(如果需要)。在某个线程被显式地关闭之前,池中的线程将一直存在。
代码实现
package cn.wideth.util;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;class MyRunnable implements Runnable {@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + " is running...");}}public class MyNewFixedThreadPool {public static void main(String[] args) {ExecutorService executorService = Executors.newFixedThreadPool(5);MyRunnable myRunnable = new MyRunnable();for (int i = 0; i < 10; i++) {executorService.execute(myRunnable);}System.out.println("线程任务开始执行");executorService.shutdown();}}
运行结果:
多个线程池。
底层实现
/*** 核心线程池大小=传入参数* 最大线程池大小为传入参数* 线程过期时间为0ms* LinkedBlockingQueue作为工作队列*/
public static ExecutorService newFixedThreadPool(int nThreads) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
}
可以看到,FixedThreadPool 的核心线程数和最大线程数都是指定值,也就是说当线程池中的线程数超过核心线程数后,任务都会被放到阻塞队列中。
此外 keepAliveTime 为 0,也就是多余的空余线程会被立即终止(由于这里没有多余线程,这个参数也没什么意义了)。
单线程线程池。而这里选用的阻塞队列是 LinkedBlockingQueue,使用的是默认容量 Integer.MAX_VALUE,相当于没有上限。
因此这个线程池执行任务的流程如下:
FixedThreadPool 用于负载比较重的服务器,为了资源的合理利用,需要限制当前线程数量。
创建一个可根据需要创建新线程的线程池,但是在以前构造的线程可用时将重用它们。对于执行很多短期异步任务的程序而言,这些线程池通常可提高程序性能。调用 execute 将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。因此,长时间保持空闲的线程池不会使用任何资源。
java 线程池。代码实现
package cn.wideth.util;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;class MyRunnable implements Runnable {@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + " is running...");}}public class MyNewCachedThreadPool {public static void main(String[] args) {ExecutorService executorService = Executors.newCachedThreadPool();MyRunnable myRunnable = new MyRunnable();for (int i = 0; i < 10; i++) {executorService.execute(myRunnable);}System.out.println("线程任务开始执行");executorService.shutdown();}
}
运行结果
底层实现
/*** 核心线程池大小=0* 最大线程池大小为Integer.MAX_VALUE* 线程过期时间为60s* 使用SynchronousQueue作为工作队列*/
public static ExecutorService newCachedThreadPool() {return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());
}
线程和线程池。可以看到,CachedThreadPool 没有核心线程,非核心线程数无上限,也就是全部使用外包,但是每个外包空闲的时间只有 60 秒,超过后就会被回收。
CachedThreadPool 使用的队列是 SynchronousQueue,这个队列的作用就是传递任务,并不会保存。
因此当提交任务的速度大于处理任务的速度时,每次提交一个任务,就会创建一个线程。极端情况下会创建过多的线程,耗尽 CPU 和内存资源。
它的执行流程如下:
java多线程和线程池,CachedThreadPool 用于并发执行大量短期的小任务,或者是负载较轻的服务器。
创建一个线程池,它可安排在给定延迟后运行命令或者定期地执行。
代码实现
package cn.wideth.util;import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;class MyRunnable implements Runnable {@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + " is running...");}}public class MyNewScheduledThreadPool {public static void main(String[] args) {ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);MyRunnable myRunnable = new MyRunnable();for (int i = 0; i < 5; i++) {// 参数1:目标对象,参数2:隔多长时间开始执行线程,参数3:执行周期,参数4:时间单位scheduledExecutorService.scheduleAtFixedRate(myRunnable, 1, 2, TimeUnit.SECONDS);}System.out.println("线程任务开始执行");}
}
运行结果
线程池?
底层实现
/*** 核心线程池大小=传入参数* 最大线程池大小为Integer.MAX_VALUE* 线程过期时间为0ms* DelayedWorkQueue作为工作队列*/
public ScheduledThreadPoolExecutor(int corePoolSize) {super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,new DelayedWorkQueue());
}
ScheduledThreadPoolExecutor 的执行流程如下:
具体执行任务的步骤也比较复杂:
java线程池有几种?ScheduledThreadPoolExecutor 用于需要多个后台线程执行周期任务,同时需要限制线程数量的场景。
本文介绍了4种常见的线程池,但是现在推荐使用自定义线程池,不过在平时开发中还是使用的比较多的。
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态