![](https://s5-media.51cto.com/ost/pc/static/noavatar.gif)
回复
//Executors.java
public static ExecutorService newFixedThreadPool( int{
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
//Executors.java
public static ExecutorService newCachedThreadPool(){
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
//Executors.java
public ScheduledThreadPoolExecutor( int corePoolSize,
ThreadFactory threadFactory){
super(corePoolSize, Integer.MAX_VALUE,
DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
new DelayedWorkQueue(), threadFactory);
}
//指定延迟执行时间
public <V> ScheduledFuture<V>
schedule(Callable<V> callable, long
//Executors.java
public static ExecutorService newSingleThreadExecutor(){
return new FinalizableDelegatedExecutorService
( new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>())); //无界队列
}
public List<Runnable> shutdownNow(){
...
final ReentrantLock mainLock = this.mainLock;
mainLock.lock(); //加锁
try {
checkShutdownAccess();
advanceRunState(STOP);
interruptWorkers(); //interrupt关闭线程
tasks = drainQueue(); //未执行任务
...
先考虑下为啥线程池的线程不会被释放,它是怎么管理线程的生命周期的呢
//ThreadPoolExecutor.Worker.class
final void runWorker(Worker w){
...
//工作线程会进入一个循环获取任务执行的逻辑
while (task != null || (task = getTask()) != null)
...
}
private Runnable getTask(){
...
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS)
: workQueue.take(); //线程会阻塞挂起等待任务,
...
}
可以看出,无任务执行时,线程池其实是利用阻塞队列的take方法挂起,从而维持核心线程的存活
//Worker class,一个worker一个线程
Worker(Runnable firstTask) {
//禁止新线程未开始就被中断
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread( this);
}
final void runWorker(Worker w){
....
//对应构造Worker是的setState(-1)
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
....
w.lock(); //加锁同步
....
try {
...
task.run();
afterExecute(task, null);
} finally {
....
w.unlock(); //释放锁
}
worker继承AQS的意义:A 禁止线程未开始就被中断;B 同步runWorker方法的处理逻辑
“A handler for rejected tasks that runs the rejected task directly in the calling thread of the {@code execute} method, unless the executor has been shut down, in which case the task is discarded.”
如果任务被拒绝了,则由「提交任务的线程」执行此任务
ForkJoinPool和ThreadPoolExecutor不同,它适合执行可以分解子任务的任务,如树的遍历,归并排序等一些递归场景
当线程执行完自己deque的任务,且其他线程deque还有多的任务,则会启动窃取策略,从其他线程deque队尾获取线程
public class ForkJoinPoolTest {
public static void main(String[] args) throws{
ForkJoinPool forkJoinPool = new ForkJoinPool();
for ( int i = 0; i < 10; i++) {
ForkJoinTask task = forkJoinPool.submit( new Fibonacci(i));
System.out.println(task.get());
}
}
static class Fibonacci extends RecursiveTask<Integer> {
int n;
public Fibonacci( int{ this.n = n; }
@Override
protected Integer compute(){
if (n <= 1) { return n; }
Fibonacci fib1 = new Fibonacci(n - 1);
fib1.fork(); //相当于开启新线程执行
Fibonacci fib2 = new Fibonacci(n - 2);
fib2.fork(); //相当于开启新线程执行
return fib1.join() + fib2.join(); //合并阻塞返回结果
}
}
}
文章转载自公众号:潜行前行