延时线程池-递增延时执行任务

一.延时线程池-递增延时执行任务

创建延时线程池,让任务获取该线程池,当任务执行失败时,根据自身算法将自身任务改变延时时间后再次放入延迟线程池,此例子仅是简单思路与流程
\color{red}{待扩展仅记录}


public class mao {
    public static void main(String[] args) {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(9);
        scheduledExecutorService.schedule(new RunMao("任务1",5,5,20,scheduledExecutorService),10, TimeUnit.SECONDS);
        scheduledExecutorService.schedule(new RunMao("任务2",5,5,20,scheduledExecutorService),10, TimeUnit.SECONDS);
        scheduledExecutorService.schedule(new RunMao("任务3",5,5,20,scheduledExecutorService),10, TimeUnit.SECONDS);
        scheduledExecutorService.schedule(new RunMao("任务4",5,5,20,scheduledExecutorService),10, TimeUnit.SECONDS);
        scheduledExecutorService.schedule(new RunMao("任务5",5,5,20,scheduledExecutorService),10, TimeUnit.SECONDS);
        scheduledExecutorService.schedule(new RunMao("任务6",5,5,20,scheduledExecutorService),10, TimeUnit.SECONDS);
        scheduledExecutorService.schedule(new RunMao("任务7",5,5,20,scheduledExecutorService),10, TimeUnit.SECONDS);
        scheduledExecutorService.schedule(new RunMao("任务8",5,5,20,scheduledExecutorService),10, TimeUnit.SECONDS);
        scheduledExecutorService.schedule(new RunMao("任务9",5,5,20,scheduledExecutorService),10, TimeUnit.SECONDS);
        scheduledExecutorService.shutdown();
    }


}

class RunMao implements Runnable{

    private String name ;
    private int count = 1;
    private int loalTime;
    private int everyTime;
    private int maxTime;

    private ScheduledExecutorService scheduledExecutorService;

    public RunMao(String name, int loalTime,int everyTime,int maxTime,ScheduledExecutorService scheduledExecutorService){
        this.name = name;
        this.loalTime = loalTime;
        this.everyTime = everyTime;
        this.scheduledExecutorService = scheduledExecutorService;
        this.maxTime = maxTime;
    }

    @Override
    public void run() {
        System.out.println("任务名---:" + name+"线程名:"+Thread.currentThread().getName()+"第"+count+"次通知"+",当前延时"+loalTime+",每次延迟时间"+everyTime+" 最长延时时间"+maxTime);
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(loalTime < maxTime){
            loalTime+= everyTime;
            loalTime = loalTime > maxTime ? maxTime : loalTime;
            count++;
            scheduledExecutorService.schedule(this,loalTime, TimeUnit.SECONDS);
        }else{
            System.out.println("任务名---:" + name +"任务完全结束");
        }
        System.out.println("--------------------------------------------------------------");


    }
}

推荐阅读更多精彩内容