学習プロセスのビデオを見る:[Crazy God Says Java]
https://www.bilibili.com/video/BV1B7411L7tE?p=13
ああ、とても良心的な先生をサポートするためにみんなを歓迎します!
スレッドプールのソースコードを作成する3つの方法
実際、スレッドプールはThreadPoolExecutorを作成することによって作成されます
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE, //21亿,导致OOM
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
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;
}
スレッドプールを手動で作成する
Javaコード
package com.add;
import java.util.concurrent.*;
/**
* Created by zjl
* 2020/11/25
**/
/*** new ThreadPoolExecutor.AbortPolicy() // 银行满了,还有人进来,不处理这个人的,抛出异 常
* * new ThreadPoolExecutor.CallerRunsPolicy() // 哪来的去哪里!
* * new ThreadPoolExecutor.DiscardPolicy() //队列满了,丢掉任务,不会抛出异常!
* * new ThreadPoolExecutor.DiscardOldestPolicy() //队列满了,尝试去和最早的竞争,也不会 抛出异常!
* */
public class ExecutorsTest2 {
public static void main(String[] args) {
//自定义线程池
ExecutorService threadPool = new ThreadPoolExecutor(
2, //核心线程数
7, //核心最大线程数
1, //超时时间 1s,超过1秒没人使用,会断开线程
TimeUnit.SECONDS, //超时单位 s
new LinkedBlockingDeque<>(3), //阻塞队列 大小设置3
Executors.defaultThreadFactory(), // 线程工厂:创建线程的,一般不用动
new ThreadPoolExecutor.AbortPolicy() //拒绝策略
);
try {
for (int i = 1; i <= 2; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName());
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
}
}
forループの数が2に設定されている場合。
現時点では、コアスレッドの数は十分です。
forループの数が4に設定されている場合:
現時点では、コアスレッドの数は十分ではありませんが、スレッドは2つしかなく、ブロッキングキューのサイズは3であり、さらに2つを格納するのに十分です。スレッドなので、実行中のスレッドは2つだけです。
forループの数が6に設定されている場合:
この時点では、コアスレッドの数は使用するのに十分ではなく、さらに4つのスレッドがあり、ブロッキングキューのサイズは3であり、余分なものを格納するのに十分ではありません4スレッドなので、3つ以上のスレッドが実行されています。
forループの数が19に設定されている
場合:最大収容力はスレッドの最大数+ブロッキングキューの数= 7 + 3 = 10
この時点で、最大収容力を超えており、この拒否戦略は次のようになります。拒否の例外を報告します。
pool-1-thread-1
pool-1-thread-3
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4
pool-1-thread-2
pool-1-thread-1
pool-1-thread-2
pool-1-thread-5
pool-1-thread-4
pool-1-thread-4
pool-1-thread-3
pool-1-thread-4
pool-1-thread-7
pool-1-thread-5
pool-1-thread-2
pool-1-thread-6
pool-1-thread-1
java.util.concurrent.RejectedExecutionException: Task com.add.ExecutorsTest2$$Lambda$1/668386784@10f87f48 rejected from java.util.concurrent.ThreadPoolExecutor@b4c966a[Running, pool size = 7, active threads = 3, queued tasks = 0, completed tasks = 15]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
at com.add.ExecutorsTest2.main(ExecutorsTest2.java:30)
Process finished with exit code 0