ScheduledThreadPoolExecutor多线程处理

1.作用

ScheduledThreadPoolExecutor用于定时任务,这里的定时意义在于:适用于多个后台线程执行周期性任务

2.ScheduledThreadPoolExecutor类

 0.先看下ScheduledThreadPoolExecutor类,继承了ThreadPoolExecutor类,实现ScheduledExecutorService类

1.创建ScheduledThreadPoolExecutor的方法如下:

corePoolSize是线程池中的核心线程数,ThreadFactory是线程

2.有以下几种方法

  • schedule(Runnable command, long delay, TimeUnit unit) // 无返回值的延迟任务
  • schedule(Callable callable, long delay, TimeUnit unit) // 有返回值的延迟任务
  • scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) // 固定频率周期任务
  • scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) // 固定延迟周期任务

 

3.代码例子

1. scheduleAtFixedRate

package com.demo;


import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Author:xiaxia
 * @Date:2021/7/27
 */
@Slf4j
public class ThreadTest {

    public static void main(String[] args){
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
        scheduledThreadPool.scheduleAtFixedRate(() -> {
            try {
                sleep(1000);               // 睡眠 1s,
                log.info("run task");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //log.info("run task");
        }, 1, 2, TimeUnit.SECONDS);
    }

    private static void sleep(int i) throws InterruptedException {
        Thread.sleep(1000);
    }


}

输出如下:

 

2.schedule

public class ThreadTest {

    public static void main(String[] args){
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
        try {
            //schedule to run after sometime
            System.out.println("Current Time = "+getNowDate());
            for(int i=0; i<3; i++){
                Thread.sleep(1000);
                WorkerThread worker = new WorkerThread();
                //延迟5秒后执行
                scheduledThreadPool.schedule(worker, 100, TimeUnit.SECONDS);
            }
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        scheduledThreadPool.shutdown();
        while(!scheduledThreadPool.isTerminated()){
            //wait for all tasks to finish
        }
        System.out.println("Finished all threads");
    }

    /**
     * 获取现在时间
     *
     * @return 返回时间类型 yyyy-MM-dd HH:mm:ss
     */
    public static String getNowDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter;
        formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String ctime = formatter.format(currentTime);
        return ctime;

    }
}

输出如下:

参考文档:https://www.cnblogs.com/sanzao/p/10760641.html