package com.javacode2022.threadpool;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author:lijinhao
* @date:2022/9/5 22:42
* @useful:
* @modify
* ===================================================
* modifier modifytime description
* ===================================================
*/
@Slf4j
public class WebSysDemo1 {
/*// 创建一个操作Thread中存放请求任务追踪id口袋的对象
static ThreadLocal<String> traceIdKD = new ThreadLocal<>();*/
// 创建一个操作Thread中存放请求任务追踪id口袋的对象,自线程可以继承父线程中的内容
static InheritableThreadLocal<String> traceIdKD = new InheritableThreadLocal<>();
static AtomicInteger threadIndex = new AtomicInteger(0);
// 处理请求的线程池
static ThreadPoolExecutor disposeRequestExecutor = new ThreadPoolExecutor(3, 3, 60,
TimeUnit.SECONDS, new LinkedBlockingDeque<>(), r -> {
Thread thread = new Thread(r);
thread.setName("pooThread--" + threadIndex.incrementAndGet());
return thread;
});
// 记录日志
public static void log(String msg) {
/*log.info(msg);*/
String traceId = traceIdKD.get();
log.info("[模拟请求{}] {}", traceId, msg);
}
// 模拟controller
public static void controller(List<String> dataList) {
log("接收请求");
service(dataList);
}
// 模拟service
public static void service(List<String> dataList) {
log("执行业务");
// dao(dataList);
daoNew(dataList);
}
// 模拟dao
public static void dao(List<String> dataList) {
log("执行数据库操作");
// for (String s : dataList) {
// log("插入数据" + s + "成功");
// }
dataList.forEach(data -> {
log("插入数据" + data + "成功");
});
}
// 模拟dao(多线程并发执行)
public static void daoNew(List<String> dataList) {
int dataSize = dataList.size();
CountDownLatch countDownLatch = new CountDownLatch(dataSize);
log("执行数据库操作(多线程)");
String threadName = Thread.currentThread().getName();
// 模拟插入数据
dataList.forEach(data ->{
new Thread(()->{
// 模拟数据库操作耗时100毫秒
try {
TimeUnit.MILLISECONDS.sleep(100);
log("插入数据["+ data + "]成功,主线程:" + threadName);
} catch (InterruptedException e) {
log.error("你的程序异常啦!!!", e);
} finally {
countDownLatch.countDown();
}
}).start();
});
// 等待上边的dataList处理完毕
try {
countDownLatch.await();
} catch (InterruptedException e) {
log.error("你的程序异常啦!!!", e);
}
}
public static void main(String[] args) {
List<String> dataList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
dataList.add("数据" + i);
}
log.info("{} 初始化数据完毕,dataList = {}" , Thread.currentThread().getName(),dataList);
// 模拟5个请求
int requestCount = 5;
for (int i = 0; i < requestCount; i++) {
String traceId = String.valueOf(i+1);
disposeRequestExecutor.execute(() -> {
try {
traceIdKD.set(traceId);
controller(dataList);
} finally {
traceIdKD.remove();
}
});
}
disposeRequestExecutor.shutdown();
log.info("模拟5个请求结束!");
}
}