大家好,又见面了,我是你们的朋友全栈君。
jdk提供了一个通过ThreadPoolExecutor创建一个线程池的类
使用给定的参数和默认的饱和策略、默认的工厂方法创建线程池
ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue)
使用给定的参数和默认的工厂方法创建线程池
ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler)
使用给定的参数和默认的饱和策略(AbortPolicy)创建线程池
ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory)
使用指定的参数创建线程池
ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler)
参数说明
当队列和线程池都满了,说明线程池处于饱和的状态,那么必须采取一种策略处理提交的新任务。这个策略默认是AbortPolicy,表示无法处理新任务时抛出异常
public class ThreadPool {
/** * 线程池的基本大小 */
static int corePoolSize = 10;
/** * 线程池最大数量 */
static int maximumPoolSizeSize = 100;
/** * 线程活动保持时间 */
static long keepAliveTime = 1;
/** * 任务队列 */
static ArrayBlockingQueue workQueue = new ArrayBlockingQueue(10);
public static void main(String[] args) {
ThreadPoolExecutor executor = new ThreadPoolExecutor(
corePoolSize,
maximumPoolSizeSize,
keepAliveTime,
TimeUnit.SECONDS,
workQueue,
new ThreadFactoryBuilder().setNameFormat("XX-task-%d").build());
//提交一个任务
executor.execute(() -> System.out.println("ok"));
}
}
任务执行
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/* * Proceed in 3 steps: * * 1. If fewer than corePoolSize threads are running, try to * start a new thread with the given command as its first * task. The call to addWorker atomically checks runState and * workerCount, and so prevents false alarms that would add * threads when it shouldn't, by returning false. * * 2. If a task can be successfully queued, then we still need * to double-check whether we should have added a thread * (because existing ones died since last checking) or that * the pool shut down since entry into this method. So we * recheck state and if necessary roll back the enqueuing if * stopped, or start a new thread if there are none. * * 3. If we cannot queue task, then we try to add a new * thread. If it fails, we know we are shut down or saturated * and so reject the task. */
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/187339.html原文链接:https://javaforall.cn