package com.ruoyi.alarm.globalAlarm.service.impl;
|
|
import com.ruoyi.alarm.globalAlarm.domain.GuidePriorityQueue;
|
import com.ruoyi.alarm.globalAlarm.domain.GuideTask;
|
import org.apache.tomcat.util.threads.TaskThread;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
import org.springframework.stereotype.Component;
|
|
import java.util.Map;
|
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.PriorityBlockingQueue;
|
|
/**
|
* @ClassName QueueManager
|
* @Description:
|
* @Author 刘苏义
|
* @Date 2023/6/29 21:09
|
* @Version 1.0
|
*/
|
|
@Component
|
public class QueueManager {
|
|
@Autowired
|
private QueueTaskExecutor taskExecutor;
|
private Map<String, TaskThread> threadMap = new ConcurrentHashMap<>();
|
|
private static class TaskThread {
|
private Thread thread;
|
private GuideTask currentTask;
|
|
public TaskThread(Thread thread, GuideTask currentTask) {
|
this.thread = thread;
|
this.currentTask = currentTask;
|
}
|
|
public Thread getThread() {
|
return thread;
|
}
|
|
public GuideTask getCurrentTask() {
|
return currentTask;
|
}
|
|
public void setCurrentTask(GuideTask task) {
|
this.currentTask = task;
|
}
|
}
|
|
public void addTaskToQueue(String queueName, GuideTask task) {
|
PriorityBlockingQueue<GuideTask> guideTaskQueue = GuidePriorityQueue.cameraQueueMap.get(queueName);
|
guideTaskQueue.add(task);
|
TaskThread currentTaskThread = threadMap.get(queueName);
|
if (currentTaskThread != null && task.getPriority() > currentTaskThread.getCurrentTask().getPriority()) {
|
currentTaskThread.getThread().interrupt();
|
}
|
|
// Start a new thread if no thread is currently running for the queue
|
if (currentTaskThread == null || !currentTaskThread.getThread().isAlive()) {
|
Thread newThread = createThread(queueName, guideTaskQueue);
|
threadMap.put(queueName, new TaskThread(newThread, task));
|
newThread.start();
|
}
|
}
|
|
private Thread createThread(String queueName, PriorityBlockingQueue<GuideTask> queue) {
|
return new Thread(() -> {
|
while (!Thread.currentThread().isInterrupted()) {
|
try {
|
GuideTask task = queue.take();
|
taskExecutor.processTask(task);
|
GuidePriorityQueue.printPriorityQueue();
|
// Update the current task for the thread
|
TaskThread currentTaskThread = threadMap.get(queueName);
|
if (currentTaskThread != null) {
|
currentTaskThread.setCurrentTask(task);
|
}
|
} catch (InterruptedException e) {
|
// Thread interrupted, exit the loop
|
Thread.currentThread().interrupt();
|
}
|
}
|
}, queueName);
|
}
|
}
|