【优化】 优化线程池,避免线程过多,造成卡顿

This commit is contained in:
dlaren
2025-08-14 15:44:07 +08:00
parent 7de8565e8e
commit 6735d85f74

View File

@@ -28,46 +28,38 @@ public class TaskManager {
/** 开始任务(每秒执行一次) */
public void startTask(StuInTheExam stuInTheExam, StuTheExamInfo stuTheExamInfo, String token, AtomicInteger countdown, AtomicInteger counter) {
// 已存在就不重复启动
tasks.computeIfAbsent(token, k ->
scheduler.scheduleAtFixedRate(safe(() -> {
// 每秒 + 1
int current = counter.incrementAndGet();
// 获取当前值并递减
int remaining = countdown.decrementAndGet();
log.debug("任务 {} tick at {}", token, System.currentTimeMillis());
tasks.computeIfAbsent(token, k -> {
Runnable task = safe(() -> {
int current = counter.incrementAndGet();
int remaining = countdown.decrementAndGet();
log.debug("任务 {} tick at {}", token, System.currentTimeMillis());
if (current == stuInTheExam.getTimes()) {
// 提示学生端进行文件的上传
stuTheExamInfo.setUpload(0);
// 重新进行计时
counter.set(0);
if (current == stuInTheExam.getTimes()) {
stuTheExamInfo.setUpload(0);
counter.set(0);
}
if (remaining <= 0) {
ScheduledFuture<?> future = tasks.remove(token);
if (future != null) {
future.cancel(false);
stuTheExamInfo.setEndStatus(0);
log.info("任务 {} 已完成并取消", token);
}
// 如果计数减到0取消任务
if (remaining <= 0) {
ScheduledFuture<?> future = tasks.get(token);
if (future != null) {
future.cancel(false);
tasks.remove(token);
// 发送最后一条消息
stuTheExamInfo.setEndStatus(0);
log.info("任务 {} 已完成并取消", token);
}
}
// 时间转变
String time = formatLongDuration(remaining);
stuTheExamInfo.setTime(time);
webSocketSenderApi.sendObject(UserTypeEnum.ADMIN.getValue(), "InTheExam", stuTheExamInfo);
}), 0, 1, TimeUnit.SECONDS)
);
}
stuTheExamInfo.setTime(formatLongDuration(remaining));
webSocketSenderApi.sendObject(UserTypeEnum.ADMIN.getValue(), "InTheExam", stuTheExamInfo);
});
return scheduler.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS);
});
log.info("任务 {} 已启动", token);
}
/** 结束任务 */
public void stopTask(String token) {
ScheduledFuture<?> f = tasks.remove(token);
if (f != null) {
f.cancel(false);
ScheduledFuture<?> future = tasks.get(token);
if (future != null) {
future.cancel(false);
tasks.remove(token);
log.info("任务 {} 已停止", token);
} else {
log.warn("任务 {} 不存在", token);