常见线程池 newScheduledThreadPool 定时执行任务的线程池 简单介绍

一  定时任务

package com.aaa.threaddemo;

import static java.util.concurrent.TimeUnit.NANOSECONDS;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.xml.crypto.Data;

/*
 * 一 newScheduledThreadPool 是个啥?
 *         1 是一个线程池
 *         2 可定时执行任务
 *         3 核心线程数是固定的
 *         4 非核心线程数 2147483647
 * 
 * 
     public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
    
    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(
        corePoolSize, 
        Integer.MAX_VALUE, 
        0,        //非核心线程的生存时间是 0 马上回收。
        NANOSECONDS,
        new DelayedWorkQueue());  //一个优先级的队列      阻塞的队列,因为它实现了BlockingQueue
        
    }    
    
   DelayedWorkQueue() 优先级队列怎么用的?
        队列一般都是先进先出的,但是在定时/延时任务中,我们需要的是延迟时间短的任务先执行。
        为了解决这个问题,需要用到一种特殊的队列            
        【优先级队列】
            对插入的数据进行优先级的排序,保证优先级高的数据先执行。和往队列中插入的顺序无关。
            没能深入调查。。。。
    
    
  二  提供了两个方法可以用
  
          schedule(command, delay, unit)
          
          schedule(
          task,                  需要执行的任务
          3,                       间隔的时间
          TimeUnit.SECONDS    时间单位   秒 分 时 。。。
 );
      
        scheduleAtFixedRate(
        command,
        initialDelay,         初次执行 间隔的时间
        period,              再次执行的相隔时间
        unit                 时间的单位
)
    【注意!】
        如果只有一次间隔时间,线程结束后关闭线程池即可。      schedule(command, delay, unit)
        但是当有二次间隔时间,是不能将线程池 shutdown的!   scheduleAtFixedRate(command, initialDelay, period, unit)
         
       
 * 
 */
public class ScheduledThreadPoolDemo {
    public static void main(String[] args) {    
        Integer integer = new Integer(0);
        int maxValue = integer.MAX_VALUE;
        System.out.println("[Integer.MAX_VALUE] = " + maxValue);
        
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  //验证是否是在三秒后执行
        System.out.println(df2.format(System.currentTimeMillis()));  
        
        ExecutorService scheduledPool = Executors.newScheduledThreadPool(1);  //创建定时的线程池 核心数量 2
        ScheduledThreadDemo thread = new ScheduledThreadDemo();    
        
        Runnable task2 = new Runnable() {
            public void run() {
                System.out.println("开启任务 task2");
            }
        };
        
        ((ScheduledExecutorService) scheduledPool).schedule(thread,3,TimeUnit.SECONDS);        //1.对于thread  2. 延迟时间3后执行任务 3.单位TimeUnit.SECONDS 是 【秒】 三秒后执行
        ((ScheduledExecutorService) scheduledPool).schedule(task2,5,TimeUnit.SECONDS);        //延迟5秒后执行任务  
        
        scheduledPool.shutdown();
    }
}

class ScheduledThreadDemo extends Thread{
    @Override
    public void run() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        System.out.println(df.format(System.currentTimeMillis()));  
        System.out.println("我是线程1, 我在运行");
        System.out.println("正在运行的线程名字" + Thread.currentThread().getName());
    }
    
}

 

看结果

 

 

 

二  scheduleAtFixedRate ?

package com.aaa.threaddemo;

import static java.util.concurrent.TimeUnit.NANOSECONDS;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.xml.crypto.Data;

/*
 * 一 newScheduledThreadPool 是个啥?
 *         1 是一个线程池
 *         2 可定时执行任务
 *         3 核心线程数是固定的
 *         4 非核心线程数 2147483647
 * 
 * 
     public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
    
    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(
        corePoolSize, 
        Integer.MAX_VALUE, 
        0,        //非核心线程的生存时间是 0 马上回收。
        NANOSECONDS,
        new DelayedWorkQueue());  //一个优先级的队列      阻塞的队列,因为它实现了BlockingQueue
        
    }    
    
   DelayedWorkQueue() 优先级队列怎么用的?
        队列一般都是先进先出的,但是在定时/延时任务中,我们需要的是延迟时间短的任务先执行。
        为了解决这个问题,需要用到一种特殊的队列            
        【优先级队列】
            对插入的数据进行优先级的排序,保证优先级高的数据先执行。和往队列中插入的顺序无关。
            没能深入调查。。。。
    
    
  二  提供了两个方法可以用
  
          schedule(command, delay, unit)
          
          schedule(
          task,                  需要执行的任务
          3,                       间隔的时间
          TimeUnit.SECONDS    时间单位   秒 分 时 。。。
 );
      
        scheduleAtFixedRate(
        command,
        initialDelay,         初次执行 间隔的时间
        period,              再次执行的相隔时间
        unit                 时间的单位
)
    【注意!】
        如果只有一次间隔时间,线程结束后关闭线程池即可。      schedule(command, delay, unit)
        但是当有二次间隔时间,是不能将线程池 shutdown的!   scheduleAtFixedRate(command, initialDelay, period, unit)
         
       
 * 
 */
public class ScheduledThreadPoolDemo {
    public static void main(String[] args) {    
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  //验证是否是在三秒后执行
        System.out.println(df2.format(System.currentTimeMillis()));  
        
        ExecutorService scheduledPool = Executors.newScheduledThreadPool(1);  //创建定时的线程池 核心数量 2
        ScheduledThreadDemo thread = new ScheduledThreadDemo();    
        
        Runnable task2 = new Runnable() {
            public void run() {
                System.out.println("开启任务 task2");
            }
        };
        
        Runnable task3 = new Runnable() {
            public void run() {
                System.out.println("开启任务 task3");
            }
        };
        
        ((ScheduledExecutorService) scheduledPool).schedule(thread,3,TimeUnit.SECONDS);        //1.对于thread  2. 延迟时间3后执行任务 3.单位TimeUnit.SECONDS 是 【秒】 三秒后执行
        ((ScheduledExecutorService) scheduledPool).schedule(task2,5,TimeUnit.SECONDS);        //延迟5秒后执行任务  
        
        ((ScheduledExecutorService) scheduledPool).scheduleAtFixedRate(task3, 8, 3, TimeUnit.SECONDS);  //对于task3 程序启动 8秒后执行,中间间隔3秒执行一次。
        
//        scheduledPool.shutdown();
    }
}

class ScheduledThreadDemo extends Thread{
    @Override
    public void run() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        System.out.println(df.format(System.currentTimeMillis()));  
        System.out.println("我是线程1, 我在运行");
        System.out.println("正在运行的线程名字" + Thread.currentThread().getName());
    }
    
}

 

 

查看结果

 

 

posted @ 2020-11-20 17:20  送外卖的小菜鸟  阅读(3196)  评论(0编辑  收藏  举报