zoukankan      html  css  js  c++  java
  • ScheduledThreadExecutor定时任务线程池

      ScheduledThreadPoolExecutor 继承自ThreadPoolExecutor实现了ScheduledExecutorService接口。主要完成定时或者周期的执行线程任务。

      代码如下:

    package com.itszt.test3;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;
    /**
     * ScheduledThreadExecutor,定时任务线程池
     */
    public class Test3 {
        public static void main(String[] args) {
            ScheduledExecutorService pool = Executors.newScheduledThreadPool(10);
            System.out.println("main开始时间:"+MyRunnable.now());
            for(int i=0;i<3;i++){
                MyRunnable myRunnable = new MyRunnable("thread-" + i);
                System.out.println(myRunnable.getName()+"开始时间:"+MyRunnable.now());
                pool.schedule(myRunnable,5, TimeUnit.SECONDS);//延时5秒执行
                //在一次调用完成和下一次调用开始之间有长度为delay的延迟
                //pool.scheduleWithFixedDelay(myRunnable,5,5,TimeUnit.SECONDS);
            }
            try {
                Thread.sleep(7000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            pool.shutdown();//7秒后不再接受执行线程
            while (!pool.isTerminated()){
                //等待所有线程结束
            }
            System.out.println("main结束时间:"+MyRunnable.now());
        }
    }
    class MyRunnable implements Runnable{
        private String name;
    
        public MyRunnable(String name) {
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    
        @Override
        public void run() {
            System.out.println(getName()+"true start:"+now());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(getName()+"true end:"+now());
        }
        static String now(){
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return format.format(new Date());
        }
    }
    

      代码执行结果如下:

    main开始时间:2018-03-24 21:08:06
    thread-0开始时间:2018-03-24 21:08:06
    thread-1开始时间:2018-03-24 21:08:06
    thread-2开始时间:2018-03-24 21:08:06
    thread-1true start:2018-03-24 21:08:11
    thread-2true start:2018-03-24 21:08:11
    thread-0true start:2018-03-24 21:08:11
    thread-2true end:2018-03-24 21:08:14
    thread-0true end:2018-03-24 21:08:14
    thread-1true end:2018-03-24 21:08:14
    main结束时间:2018-03-24 21:08:14  
  • 相关阅读:
    Codeforces Round #313 (Div. 1) A.Gerald's Hexagon
    COJN 0585 800604鸡蛋的硬度
    COJN 0584 800603吃糖果
    COJN 0583 800602分苹果
    COJN 0575 800601滑雪
    昨天的补记
    重构的代码
    写了一个复杂的sql语句
    一个想法
    安装了C
  • 原文地址:https://www.cnblogs.com/lizhangyong/p/8641480.html
Copyright © 2011-2022 走看看