标签:讲解 cached 钩子函数 ble 优先级 executors 添加 打印 先来
线程池和数据库的连接池是同样意思,把多个线程放在一个集合里,有任务时从集合里分配线程,当该线程完成任务后不是销毁,放入线程池等待下次任务,减少了创建和销毁线程的次数,提高系统效率,因为创建和销毁属于重操作
。如果每有一个任务就创建一个线程,大量任务涌进会导致创建过多线程而内存溢出
java.util.concurrent.Executor 提供一系列与线程池相关的接口,及其实现类,其中抽取常用的部分来讲解
UML图:
ExecutorService接口方法:
AbstractExecutorService类方法:
这个常用的类提供了创建线程池的方法,根据传入的参数不同,创建不同的线程池,先来看看构造方法
public ThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
//省略具体逻辑,单看参数
}
execute(),submit(),shutdown(),shutdownNow() 是添加任务和关闭线程池的方法,前两者进行相应逻辑判断再考虑是否创建新线程,后两者是关闭线程池,区别于后者不等其任务完成就中断线程
在Executor类中,有下面几个静态方法来快捷创建线程池,下面写三个:
public static void main(String[] args) {
//快捷线程池
ExecutorService pool = Executors.newFixedThreadPool(10);
//没有返回值
Runnable runnable = () -> System.out.println("Runnable任务");
//有返回值
Callable callable = () -> {
String msg = "Callable任务";
System.out.println(msg);
return msg;
};
//提交任务,并获取返回值
Future f1 = pool.submit(runnable);
Future f2 = pool.submit(callable);
try {
System.out.println("f1:" + f1.get());
System.out.println("f2:" + f2.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
//关闭线程池
pool.shutdown();
}
Callable任务
Runnable任务
f1:null
f2:Callable任务
submit底层是用execute实现的:
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task); //把Callable变成RunnableFuture
execute(ftask); //把RunnableFuture传入execute
return ftask;
}
Callable会被包装成RunnableFuture,在RunnableFuture的run中会调用callable的call方法,然后把返回值或异常放入该类的静态变量中
public static void main(String[] args) {
//核心线程
int corePoolSize = 5;
//最大线程
int maximumPoolSize = 10;
//保持空闲时间
long keepAliveTime = 10;
//空闲时间单位,秒
TimeUnit unit = TimeUnit.SECONDS;
//排队策略,基于数组结构的有界阻塞队列
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(5);
//设置创建线程的工厂,可以预设部分内容:eg:守护进程,优先级
ThreadFactory threadFactory = Executors.defaultThreadFactory();
//拒绝策略
RejectedExecutionHandler handler = new AbortPolicy();;
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize,
maximumPoolSize,
keepAliveTime,
unit,
workQueue,
threadFactory,
handler);
Callable callable = () -> {
String msg = "Callable任务";
System.out.println(msg);
return msg;
};
threadPoolExecutor.submit(() -> System.out.println("线程测试1"));
threadPoolExecutor.submit(callable);
}
<!-- 打印 -->
线程测试1
Callable任务
标签:讲解 cached 钩子函数 ble 优先级 executors 添加 打印 先来
原文地址:https://www.cnblogs.com/Howlet/p/12233870.html