JAVA多线程之实现用户任务排队并预估排队时长

2022-07-20,,,,

目录
  • 实现流程
  • 排队论简介
  • 代码具体实现
  • 接口测试
  • 补充知识
    • blockingqueue
    • 阻塞与非阻塞

实现流程

初始化一定数量的任务处理线程和缓存线程池,用户每次调用接口,开启一个线程处理。

假设初始化5个处理器,代码执行 blockingqueue.take 时候,每次take都会处理器队列就会减少一个,当处理器队列为空时,take就是阻塞线程,当用户处理某某任务完成时候,调用资源释放接口,在处理器队列put 一个处理器对象,原来阻塞的take ,就继续执行。

排队论简介

排队论是研究系统随机聚散现象和随机系统工作工程的数学理论和方法,又称随机服务系统理论,为运筹学的一个分支。我们下面对排队论做下简化处理,先看下图:

代码具体实现

任务队列初始化 taskqueue

import com.baomidou.mybatisplus.core.toolkit.collectionutils;
import org.springframework.stereotype.component;
 
import javax.annotation.postconstruct;
import java.util.optional;
import java.util.concurrent.blockingqueue;
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;
import java.util.concurrent.linkedblockingqueue;
import java.util.concurrent.atomic.atomicinteger;
 
/**
 * 初始化队列及线程池
 * @author tarzan
 *
 */
@component
public class taskqueue {
    //处理器队列
    public static blockingqueue<taskprocessor> taskprocessors;
    //等待任务队列
    public static blockingqueue<compiletask> waittasks;
    //处理任务队列
    public static blockingqueue<compiletask> executetasks;
    //线程池
    public static executorservice exec;
    //初始处理器数(计算机cpu可用线程数)
    public static integer processornum=runtime.getruntime().availableprocessors();
 
    /**
     * 初始化处理器、等待任务、处理任务队列及线程池
     */
    @postconstruct
    public static void initequipmentandusersqueue(){
        exec = executors.newcachedthreadpool();
        taskprocessors =new linkedblockingqueue<taskprocessor>(processornum);
        //将空闲的设备放入设备队列中
        setfreedevices(processornum);
        waittasks =new linkedblockingqueue<compiletask>();
        executetasks=new linkedblockingqueue<compiletask>(processornum);
    }
 
 
    /**
     * 将空闲的处理器放入处理器队列中
     */
    private static void setfreedevices(int num) {
        //获取可用的设备
        for (int i = 0; i < num; i++) {
            taskprocessor dc=new taskprocessor();
            try {
                taskprocessors.put(dc);
            } catch (interruptedexception e) {
                e.printstacktrace();
            }
        }
    }
 
 
 
    public static compiletask getwaittask(long clazzid) {
        return get(taskqueue.waittasks,clazzid);
    }
 
    public static compiletask getexecutetask(long clazzid) {
        return get(taskqueue.executetasks,clazzid);
    }
 
 
    private static compiletask get(blockingqueue<compiletask> users, long clazzid) {
        compiletask compiletask =null;
        if (collectionutils.isnotempty(users)){
            optional<compiletask> optional=users.stream().filter(e->e.getclazzid().longvalue()==clazzid.longvalue()).findfirst();
            if(optional.ispresent()){
                compiletask =  optional.get();
            }
        }
        return compiletask;
    }
 
    public static integer getsort(long clazzid) {
        atomicinteger index = new atomicinteger(-1);
        blockingqueue<compiletask> compiletasks = taskqueue.waittasks;
        if (collectionutils.isnotempty(compiletasks)){
            compiletasks.stream()
                    .filter(e -> {
                        index.getandincrement();
                        return e.getclazzid().longvalue() == clazzid.longvalue();
                    })
                    .findfirst();
        }
        return index.get();
    }
 
    //单位秒
    public static int estimatedtime(long clazzid){
        return  estimatedtime(60,getsort(clazzid)+1);
    }
 
    //单位秒
    public static int estimatedtime(int cellms,int num){
         int a= (num-1)/processornum;
         int b= cellms*(a+1);
        return  b;
    }
 
 
 
 
 

编译任务类 compiletask

import lombok.data;
import org.springblade.core.tool.utils.springutil;
import org.springblade.gis.common.enums.datascheduleenum;
import org.springblade.gis.dynamicds.service.dynamicdatasourceservice;
import org.springblade.gis.modules.feature.schedule.service.datascheduleservice;
 
import java.util.date;
 
 
@data
public class compiletask implements runnable {
    //当前请求的线程对象
    private long clazzid;
    //用户id
    private long userid;
    //当前请求的线程对象
    private thread thread;
    //绑定处理器
    private taskprocessor taskprocessor;
    //任务状态
    private integer status;
    //开始时间
    private date starttime;
    //结束时间
    private date endtime;
 
    private datascheduleservice datascheduleservice= springutil.getbean(datascheduleservice.class);
 
    private dynamicdatasourceservice datasourceservice= springutil.getbean(dynamicdatasourceservice.class);
 
    @override
    public void run() {
        compile();
    }
 
    /**
     * 编译
     */
    public void compile() {
        try {
            //取出一个设备
            taskprocessor taskprocessor = taskqueue.taskprocessors.take();
            //取出一个任务
            compiletask compiletask = taskqueue.waittasks.take();
            //任务和设备绑定
            compiletask.settaskprocessor(taskprocessor);
            //放入
            taskqueue.executetasks.put(compiletask);
            system.out.println(datascheduleenum.deal_with.getname()+" "+userid);
            //切换用户数据源
            datasourceservice.switchdatasource(userid);
            //添加进度
            datascheduleservice.addschedule(clazzid, datascheduleenum.deal_with.getstate());
        } catch (interruptedexception e) {
            system.err.println( e.getmessage());
        }
    }
 
}

任务处理器 taskprocessor 

import lombok.data;
 
import java.util.date;
 
@data
public class taskprocessor {
 
    /**
     * 释放
     */
    public  static boolean release(compiletask task)  {
        boolean flag=false;
        thread thread=task.getthread();
        synchronized (thread) {
            try {
                if(null!=task.gettaskprocessor()){
                    taskqueue.taskprocessors.put(task.gettaskprocessor());
                    taskqueue.executetasks.remove(task);
                    task.setendtime(new date());
                    long intervalmilli = task.getendtime().gettime() - task.getstarttime().gettime();
                    flag=true;
                    system.out.println("用户"+task.getclazzid()+"耗时"+intervalmilli+"ms");
                }
            } catch (interruptedexception e) {
                e.printstacktrace();
            }
            return flag;
        }
    }
 
}

controller控制器接口实现

import io.swagger.annotations.api;
import io.swagger.annotations.apioperation;
import org.springblade.core.tool.api.r;
import org.springblade.gis.multithread.taskprocessor;
import org.springblade.gis.multithread.taskqueue;
import org.springblade.gis.multithread.compiletask;
import org.springframework.web.bind.annotation.*;
 
import java.util.date;
 
 
@restcontroller
@requestmapping("task")
@api(value = "数据编译任务", tags = "数据编译任务")
public class compiletaskcontroller {
 
    @apioperation(value = "添加等待请求 @author tarzan liu")
    @postmapping("compile/{clazzid}")
    public r<integer> compile(@pathvariable("clazzid") long clazzid) {
        compiletask checkuser=taskqueue.getwaittask(clazzid);
        if(checkuser!=null){
            return  r.fail("已经正在排队!");
        }
        checkuser=taskqueue.getexecutetask(clazzid);
        if(checkuser!=null){
            return  r.fail("正在执行编译!");
        }
        //获取当前的线程
        thread thread=thread.currentthread();
        //创建当前的用户请求对象
        compiletask compiletask =new compiletask();
        compiletask.setthread(thread);
        compiletask.setclazzid(clazzid);
        compiletask.setstarttime(new date());
        //将当前用户请求对象放入队列中
        try {
            taskqueue.waittasks.put(compiletask);
        } catch (interruptedexception e) {
            e.printstacktrace();
        }
        taskqueue.exec.execute(compiletask);
        return r.data(taskqueue.waittasks.size()-1);
    }
 
    @apioperation(value = "查询当前任务前还有多少任务等待 @author tarzan liu")
    @postmapping("sort/{clazzid}")
    public r<integer> sort(@pathvariable("clazzid") long clazzid) {
        return r.data(taskqueue.getsort(clazzid));
    }
 
    @apioperation(value = "查询当前任务预估时长 @author tarzan liu")
    @postmapping("estimate/time/{clazzid}")
    public r<integer> estimatedtime(@pathvariable("clazzid") long clazzid) {
        return r.data(taskqueue.estimatedtime(clazzid));
    }
 
    @apioperation(value = "任务释放 @author tarzan liu")
    @postmapping("release/{clazzid}")
    public r<boolean> release(@pathvariable("clazzid") long clazzid) {
        compiletask task=taskqueue.getexecutetask(clazzid);
        if(task==null){
            return  r.fail("资源释放异常");
        }
        return r.status(taskprocessor.release(task));
    }
 
    @apioperation(value = "执行 @author tarzan liu")
    @postmapping("exec")
    public r exec() {
        long start=system.currenttimemillis();
        for (long i = 1l; i < 100; i++) {
            compile(i);
        }
        system.out.println("消耗时间:"+(system.currenttimemillis()-start)+"ms");
        return r.status(true);
    }
}

接口测试

根据任务id查询该任务前还有多少个任务待执行

根据任务id查询该任务预估执行完成的剩余时间,单位秒

补充知识

blockingqueue

blockingqueue即阻塞队列,它是基于reentrantlock,依据它的基本原理,我们可以实现web中的长连接聊天功能,当然其最常用的还是用于实现生产者与消费者模式,大致如下图所示:

在java中,blockingqueue是一个接口,它的实现类有arrayblockingqueue、delayqueue、 linkedblockingdeque、linkedblockingqueue、priorityblockingqueue、synchronousqueue等,它们的区别主要体现在存储结构上或对元素操作上的不同,但是对于take与put操作的原理,却是类似的。

阻塞与非阻塞

入队

offer(e e):如果队列没满,立即返回true; 如果队列满了,立即返回false-->不阻塞

put(e e):如果队列满了,一直阻塞,直到队列不满了或者线程被中断-->阻塞

offer(e e, long timeout, timeunit unit):在队尾插入一个元素,,如果队列已满,则进入等待,直到出现以下三种情况:-->阻塞

被唤醒

等待时间超时

当前线程被中断

出队

poll():如果没有元素,直接返回null;如果有元素,出队

take():如果队列空了,一直阻塞,直到队列不为空或者线程被中断-->阻塞

poll(long timeout, timeunit unit):如果队列不空,出队;如果队列已空且已经超时,返回null;如果队列已空且时间未超时,则进入等待,直到出现以下三种情况:

被唤醒

等待时间超时

当前线程被中断 

到此这篇关于java多线程之实现用户任务排队并预估排队时长的文章就介绍到这了,更多相关java 多线程 用户任务排队内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《JAVA多线程之实现用户任务排队并预估排队时长.doc》

下载本文的Word格式文档,以方便收藏与打印。