2 Commits

Author SHA1 Message Date
wonder 9458d09f69 🔄Update: 创建线程池 2025-11-10 21:32:43 +08:00
wonder b2ab34c344 📝Docs: 更新 README 2025-11-10 19:31:05 +08:00
3 changed files with 21 additions and 35 deletions
+1 -1
View File
@@ -1 +1 @@
https://doc.hutool.cn/pages/ExecutorBuilder
> 注意:Java ExecutorService 使用的默认等待队列是无限大小的 `LinkedBlockingQueue`,容易 OOM,不推荐使用
-6
View File
@@ -23,12 +23,6 @@
</parent>
<dependencies>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<version>5.8.31</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
@@ -1,42 +1,34 @@
package cn.hezhaohui.threadpool;
import cn.hutool.core.thread.ExecutorBuilder;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
@Slf4j
public class ThreadPoolApplication {
public static void main(String[] args) {
ExecutorBuilder builder = new ExecutorBuilder();
ThreadPoolExecutor executor = builder
.setCorePoolSize(5)
.setMaxPoolSize(10)
.setKeepAliveTime(0)
.setHandler(new RejectedExecutionHandler(){
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
log.info(r.toString());
}
})
.setWorkQueue(new ArrayBlockingQueue<>(100))
.build();
for (int i = 1; i <= 1000; i++) {
executor.execute(() -> {
log.info("Hello");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(2);
for (int i = 0; i < 100000000; i++) {
executorService.execute(() -> {
StringBuilder builder = new StringBuilder();
int random = new Random().nextInt(1000);
for (int j = 1; j < random; j++) {
builder.append(j);
}
try {
TimeUnit.HOURS.sleep(1);
} catch (InterruptedException e) {
log.error("[Error]");
}
log.info(builder.toString());
});
}
executor.shutdown();
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.HOURS);
}
}