スレッドプール
3つの方法、7つのパラメーター、4つの拒否マニュアル
プーリング技術
プログラムの実行の性質は、システムリソースを消費します。リソースの使用を最適化します!=>プーリング技術
スレッドプール接続プールメモリプールオブジェクトプールの作成と破棄はリソースの浪費です
プーリング技術は事前にいくつかのリソースを準備し、誰かがそれを使用したい場合は、ここに来てそれを使い切ったら私に返してください
スレッドプールの利点
1.リソース消費を削減する
2.応答速度を改善する
3.便利な管理
スレッドの再利用。並行管理スレッドの最大数を制御できます
3つの方法
package com.xizi.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//Executors 工具类 三大方法
public class Demo01 {
public static void main(String[] args) {
//单个线程
// ExecutorService threadPool = Executors.newSingleThreadExecutor();
//创建一个固定的线程池的大小
// ExecutorService threadPool = Executors.newFixedThreadPool(5);
//可伸缩,遇强则强 遇弱则弱
ExecutorService threadPool = Executors.newCachedThreadPool();
try {
for (int i = 0; i < 100; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+" ok");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
}
}
7パラメータ
本质ThreadPoolExecutor()
源码
public ThreadPoolExecutor(int corePoolSize,//核心线程池大小
int maximumPoolSize,//最大核心线程池大小
long keepAliveTime,//超时了没有人调用就会释放
TimeUnit unit,//超时单位
BlockingQueue<Runnable> workQueue,//阻塞队列
ThreadFactory threadFactory,//线程工厂,创建线程
RejectedExecutionHandler handler //拒绝策略
) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
スレッドプールを手動で作成する
package com.xizi.pool;
import java.util.concurrent.*;
//Executors 工具类 三大方法
public class Demo01 {
public static void main(String[] args) {
//单个线程
// ExecutorService threadPool = Executors.newSingleThreadExecutor();
//创建一个固定的线程池的大小
// ExecutorService threadPool = Executors.newFixedThreadPool(5);
//可伸缩,遇强则强 遇弱则弱
// ExecutorService threadPool = Executors.newCachedThreadPool();
//自定义线程池 工作中 ThreadPoolExecutor() 安全
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
2,
5,
3,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
// 1. new ThreadPoolExecutor.AbortPolicy()//银行还有人进来,不处理这个人,抛出异常
// 2. new ThreadPoolExecutor.CallerRunsPolicy() //哪来的去哪里
// 3. new ThreadPoolExecutor.DiscardPolicy() //队列满了 丢掉任务,不会抛出异常
new ThreadPoolExecutor.DiscardOldestPolicy()// 队列满了,尝试和最早的竞争 不会抛出异常
);
try {
for (int i = 0; i < 9; i++) {
//线程池创建
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+" ok");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
}
}
最大のスレッドを定義する方法は?(チューニング)
// 1。CPUを集中的に使用するコアは、CPUの最高の効率を保証するためのほんの一部です
Runtime.getRuntime()。availableProcessors();
//2.IO集中型。プログラム内のIO消費スレッドを特定する