使用Executors创建ScheduledThreadPoolExecutor的方法构造如下:
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public static ScheduledExecutorService newScheduledThreadPool(
int corePoolSize, ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}
使用Executors创建SingleThreadScheduledExecutor的方法构造如下:
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory));
}
ScheduledExecutorService scheduledThreadPoolExecutor=Executors.newScheduledThreadPool(5);
ScheduledExecutorService singleThreadScheduledExecutor=Executors.newSingleThreadScheduledExecutor();
注意:DelayQueue是一个无界队列,所以ThreadPoolExecutor的maximumPoolSize在ScheduledThreadPoolExecutor中无意义。
ScheduledThreadPoolExecutor的执行主要分为以下两个部分:
创建一个Runnable的对象,然后使用ScheduledThreadPoolExecutor的Scheduled()来执行延迟任务。
public ScheduledFuture schedule(Runnable command,long delay, TimeUnit unit);
参数解析
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @authorSaint
* @version 1.0
* @date 2020/8/9 15:05
*/
public class Main {
public static void main(String[] args) {
ScheduledExecutorService scheduledThreadPoolExecutor= Executors.newScheduledThreadPool(1);
long cur = System.currentTimeMillis();
System.out.println("延迟要开始了");
scheduledThreadPoolExecutor.schedule(new Runnable() {
@Override
public void run() {
System.out.println("Hello, World!");
}
//0表示首次执行任务的延迟时间,1000表示每次执行任务的间隔时间,TimeUnit.MILLISECONDS执行的时间间隔数值单位
}, 2000, TimeUnit.MILLISECONDS);
long stop = System.currentTimeMillis();
}
}
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit);
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit);
案例代码
package cn.com.wind.windabc.shceduledthreadpool;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 定时任务,并增加执行次数限制
* @author Saint
* @version 1.0
* @date 2020/8/9 15:14
*/
public class ScheduledMultiThreadTool {
private static Integer count =1;
MyTimerTask myTimerTask = new MyTimerTask();
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(2);
public void start(){
try {
//一秒执行一次
scheduled.scheduleAtFixedRate(myTimerTask, 0,1, TimeUnit.SECONDS);
while (!scheduled.isTerminated()){
lock.readLock().lock();
if (count >20){
scheduled.shutdown();
}
lock.readLock().unlock();
}
}catch(Exception e){
e.printStackTrace();
}
System.out.println("Finished all threads");
}
private class MyTimerTask implements Runnable {
@Override
public void run(){
lock.writeLock().lock();
System.out.println("第 "+count+ " 次执行任务,count="+count);
count ++;
lock.writeLock().unlock();
}
}
public static void main(String[] args) {
new ScheduledMultiThreadTool().start();
}
}
限制程序执行的次数:如果是单线程,那么可以直接定义一个静态变量count,每执行一次,count加一,如果count大于某个值就调用shutdown或者shutdownNow函数;如果是多线程,稍微要复杂一点,但是原理也是一样的。定义一个静态变量count,没执行一个也是count加一,只不过在执行加一操作之前需要加锁,执行完之后需要解锁
附:时间单位
毫秒:TimeUnit.MILLISECONDS
秒:TimeUnit.SECONDS
分钟:TimeUnit.MINUTES
小时:TimeUnit.HOURS
天:TimeUnit.DAYS
SingleThreadScheduledExecutor与ScheduledThreadPoolExecutor使用方法类似。
了解完ScheduledThreadPoolExecutor的创建方法和内置的几个schedule()方法后,使用起来还是很简单的。
我们主要记住两个类:SingleThreadScheduledExecutor、ScheduledThreadPoolExecutor