测试代码
public class ThreadPoolModule {
public static void main(String[] args) {
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 3, 0,
TimeUnit.SECONDS,
// 任务队列
new LinkedBlockingQueue<Runnable>(1),
// 自定义线程工厂
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
return thread;
}
},
// 自定义拒绝策率
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println("满了");
}
});
/**
* 任务1
* 线程池创建核心线程进行处理
*/
threadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println("任务1执行了!");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
/**任务2
* 创建核心线程进行处理
*
*/
threadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println("线程2执行了!");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
/**
* 任务3
* 核心线程满了,放入队列
*/
threadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println("任务3执行了!");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
/**
* 任务4
*队列满了,创建非核心线程处理
*/
threadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println("任务4执行了!");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
/**
* 任务5
* 队列满了.总线程数满了,使用拒绝策率
*/
threadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println("任务5执行了!");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
运行结果
源码解析
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);
}