线程池的execute()和submit()区别*
最近我正在学线程池,一定有很多人像我一样有疑惑,线程池的execute()和submit()都是向线程池提交一个任务,他们有什么区别??
下面我们先看一下submit()的源码:
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture<Void> ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new FutureTask<T>(callable);
}
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
从这段代码中,可以看到submit()的实现调用了execute()方法,利用了Future来获取任务执行的结果,然后返回任务执行的结果,Future是通过callable实现的。
接下来,我们看一下execute()的源码:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
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);
}
ctl作为AtomicInteger类存放了类中的两种信息,在其中由高3位来保存线程池的状态,后29位来保存此时线程池中的Woker类线程数量(由此可知,线程池中的线程数量最高可以接受大约在五亿左右)。由此可见给出的runStateOf()和workerCountOf()方法分别给出了查看线程状态和线程数量的方法。
我们先分析一下,看看jdk源码给的解释:
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.
分三步进行:
1、如果线程池中运行的线程小于corePoolSize,那么直接调用addWoker(),来添加工作线程。
并且addWoker()能自动检查线程的状态和线程池中线程的数量。
2、如果一个任务可以成功加入队列,那么我们仍然需要判断线程池的状态如果已经不是running那么会拒绝执行这一任务并执行相应的拒绝策略。如果在之前的前提下加入任务队列也失败了(比如任务队列已满),则会在不超过线程池最大线程数量的前提下建立一个工作线程来处理。
3、如果在最后的建立工作线程也失败了,那就执行任务的拒绝策略。
综上所述:
execute()和submit()的区别:
(1)execute()没有返回值,submit()有返回值;
(2)由于返回值的区别,它们的异常处理方式不同,submit()能通过Future.get()捕获异常。
https://www.cnblogs.com/wscit/p/6100476.html有详细的介绍。
参考链接: [link]https://blog.csdn.net/weixin_40318210/article/details/78070132.