private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
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);
}
线程运行状态:
running:-1 可以接收新任务,也可以处理队列里的任务
shutdown:0 不接收新的任务,可以处理队列里的任务
stop:1 不接收新的任务,不处理队列里的任务
tiding:2 不接收新的任务,不处理队列里的任务
terminated:3 不接收新的任务,不处理队列里的任务
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
10, // 核心线程数
30, // 最大线程数 0,
TimeUnit.HOURS,
new LinkedBlockingDeque<>(5) // 队列
);
提交优先级:
// 100个任务:
1)1-10 核心线程数
2)11-15 队列里,此时队列容量为5
3)16-36 新建线程,30-10 = 20个
4)拒绝策略 -- 37的时候运行报错:AbortPolicy 默认
执行优先级:
1)核心线程数
2)最大线程数
3)队列
因此,执行顺序为 1-10 16-36 11-15
ThreadPoolExcutor内部有4种拒绝策略:
1)CallerRunsPolicy:由调用execute方法提交任务的线程来执行这个任务
2) AbortPolicy:抛出异常RejectedExcutionException拒绝提交任务,default 默认用这个
3) DiscardPolicy:直接抛弃任务,不做任何处理
4) DiscardOldestPolicy:去除任务队列中的第一个任务(最旧的),重新提交
一般会自定义 RejectdExcutionHandler接口,存数据库。
/*
* Methods for creating, running and cleaning up after workers
*/
/**
* Checks if a new worker can be added with respect to current
* pool state and the given bound (either core or maximum). If so,
* the worker count is adjusted accordingly, and, if possible, a
* new worker is created and started, running firstTask as its
* first task. This method returns false if the pool is stopped or
* eligible to shut down. It also returns false if the thread
* factory fails to create a thread when asked. If the thread
* creation fails, either due to the thread factory returning
* null, or due to an exception (typically OutOfMemoryError in
* Thread.start()), we roll back cleanly.
*
* @param firstTask the task the new thread should run first (or
* null if none). Workers are created with an initial first task
* (in method execute()) to bypass queuing when there are fewer
* than corePoolSize threads (in which case we always start one),
* or when the queue is full (in which case we must bypass queue).
* Initially idle threads are usually created via
* prestartCoreThread or to replace other dying workers.
*
* @param core if true use corePoolSize as bound, else
* maximumPoolSize. (A boolean indicator is used here rather than a
* value to ensure reads of fresh values after checking other pool
* state).
* @return true if successful
*/
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
//获取当前线程状态
int rs = runStateOf(c);
// Check if queue empty only if necessary.
// 如果大于shutdown状态:返回false 不再增加线程
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
// 获取当前线程数,看是否超过最大线程数,如果超出,返回false,不再增加
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
// 如果当前线程数<最大线程数,自增+1,退出循环,后续有增加线程逻辑
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
// Worker extends AbstractQueuedSynchronizer implement Runnable, 复写run(), 调用start()运行
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
// 并发运行上锁
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
进程:操作系统会以进程为单位,分配系统资源(CPU时间片,内存等资源),是资源分配的最小单位。
线程:CPU调度的最小单位
进程间的通信方式: pipe/named pipe,signal,message queue,shared memory,semaphore(可以用来做限流),socket
线程间通信:共享内存
分布式锁: mysql zk redies
线程同步:一个线程依赖另一个线程的消息,当没有个到另一个消息时,应等待,直到消息到达时才被唤醒。
线程互斥:当多个线程需要访问同一共享资源时,任何时刻最多只允许一个线程去使用,其他线程等待,知道资源被释放。
上下文切换只能在内核模式下发生。
内核态:kernel mode Ring 0 1 2
Ring 3(用户态)
用户态:user mode
应用程序崩溃不会向影像内核的运行
应用程序一般会在以下几种情况切换到内核模式:
1)系统调用。thread, lock
2)异常事件
3)设备中断
线程的生命周期:
操作系统层面:初始状态,start()可运行状态,运行状态,休眠状态,终止状态
java: new, running, termiated, timed_waiting, waiting(.wait(),.join(),LockSupport.park()), blocked(synchronized)