123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- package cn.cslg.pas.service.importPatent;
- import cn.cslg.pas.domain.business.ImportTask;
- import cn.cslg.pas.service.business.ImportTaskService;
- import lombok.RequiredArgsConstructor;
- import org.springframework.stereotype.Service;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- /**
- * 导入专利所需的各队列和线程
- *
- * @author chenyu
- * @date 2023/10/20
- */
- @Service
- @RequiredArgsConstructor
- public class PatentQueueService {
- private final ImportTaskService importTaskService;
- private final ImportPatentFactory importPatentFactory;
- private final List<Integer> importTaskQueue = new ArrayList<>();
- private final Lock importTaskLock = new ReentrantLock();
- private final Condition importTaskCondition = importTaskLock.newCondition();
- /**
- * 从任务队列取出并执行任务
- */
- public void excuteTask() {
- while (true) {
- ImportTask importTask = new ImportTask();
- try {
- //判断任务队列是否有任务,若没有则线程等待唤醒
- if (importTaskQueue.size() == 0) {
- importTaskLock.lock();
- importTaskCondition.await();
- }
- //线程被唤醒后 ↓
- if (importTaskQueue.size() > 0) {
- //从任务队列中取出第一个任务,同时将其从任务队列中剔除
- importTask = importTaskService.getById(importTaskQueue.remove(0));
- //判断任务状态,若不存在/已完成/已暂停/已取消,则跳过继续取下一个任务
- if (importTask == null || importTask.getState().equals(2) || importTask.getState().equals(4) || importTask.getState().equals(5)) {
- continue;
- }
- //TODO 调用工厂方法
- ImportPatentImp imp = importPatentFactory.getClass(importTask.getId());
- //执行导入专利方法
- imp.startImport(importTask);
- }
- } catch (Exception e) {
- e.printStackTrace();
- //导入任务表更新数据(导入状态完成、完成时间)
- importTask.setState(2);
- importTask.setFinishTime(new Date());
- importTaskService.updateById(importTask);
- }
- }
- }
- /**
- * 唤醒生产者线程
- */
- public void awakeTasktch() {
- if (importTaskLock.tryLock()) {
- //taskLock.lock();
- importTaskCondition.signalAll();
- importTaskLock.unlock();
- }
- }
- /**
- * 添加导入专利任务到任务队列
- *
- * @param importTaskIds 任务ids
- */
- public void addImportTasksToQueue(List<Integer> importTaskIds) {
- importTaskQueue.addAll(importTaskIds);
- }
- }
|