4-3-4种线程池

文章目录
  1. 1. 四种线程池
    1. 1.0.1. ThreadPoolExecutor构造函数
    2. 1.0.2. 1.newCachedThreadPool(重用-无限线程-一个大小队列,短时间的任务好)
    3. 1.0.3. 2.newFixedThreadPool(可重用-固定线程数,无界队列)
    4. 1.0.4. 3.newScheduledThreadPool(延迟/定期执行,无线线程)
    5. 1.0.5. 4.newSingleThreadExecutor(只有一个线程,无界队列)

四种线程池

  1. 顶级接口Executor,但不是线程池,知识一个执行线程的工具。
  2. 真正线程池接口时executorService。

ThreadPoolExecutor构造函数

1
2
3
4
5
6
7
public ThreadPoolExecutor(int corePoolSize,//核心线程大小
int maximumPoolSize,//最大线程大小
long keepAliveTime,//线程缓存时间
TimeUnit unit,//前面keepAlive
BlockingQueue<Runnable> workQueue,//缓存队列
ThreadFactory threadFactory,//线程工厂
RejectedExecutionHandler handler)//拒绝策略

1.newCachedThreadPool(重用-无限线程-一个大小队列,短时间的任务好)

对于执行很多短期异步任务的程序而言,这些线程池通常可提高程序性能。

  1. 调用 execute 将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线程并添加到池中。
  2. 终止并从缓存中移除那些已有 60 秒钟未被使用的线程。

core 0, max, sychronousQueue

1
2
3
4
5
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}

2.newFixedThreadPool(可重用-固定线程数,无界队列)

core=max, linkedblockqueue

创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。

1
2
3
4
5
6
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}

3.newScheduledThreadPool(延迟/定期执行,无线线程)

core, max, delayedworkqueue

1
2
3
4
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
new DelayedWorkQueue());
}

使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
ScheduledExecutorService scheduledThreadPool= Executors.newScheduledThreadPool(3); 
scheduledThreadPool.schedule(newRunnable(){
@Override
public void run() {
System.out.println("延迟三秒");
}
}, 3, TimeUnit.SECONDS);
scheduledThreadPool.scheduleAtFixedRate(newRunnable(){
@Override
public void run() {
System.out.println("延迟 1 秒后每三秒执行一次");
}
},1,3,TimeUnit.SECONDS);

4.newSingleThreadExecutor(只有一个线程,无界队列)

core1, max1, linkedblockqueue

1
2
3
4
5
6
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}