execute 和 submit
submit和execute 本质上是没有区别的,根据源码所知,submit也是调用了execute()方法,只不过submit是有返回值的。
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture<Void> ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
执行优先级 是 核心线程>非核心线程>队列
提交优先级 是 核心线程>队列>非核心线程
//自定义线程池
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 20,
0L, TimeUnit.HOURS,
new ArrayBlockingQueue<Runnable>(10));
execute 方法源码解析
1、如果运行的线程数量 小于 corePoolSize 就用核心线程执行
2、如果核心线程被消耗玩,就放在队列里等待,等核心线程空闲,再来消费队列里的任务
3、如果核心线程池 和 队列都被消耗完,就会启用非核心线程池
execute 执行优先级 是 核心线程>队列>非核心线程
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);
}