java ScheduledExecutorService、Timer 多线程与定时任务的结合使用

日萌社

人工智能AI:Keras PyTorch MXNet TensorFlow PaddlePaddle 深度学习实战(不定时更新)


 

第一种方式:多线程 + 定时任务 执行,会专门使用一个线程执行 定时任务

package com.nginxlog;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

public class ScheduledExecutorServiceTest
{
    public static void main(String[] args)
    {
        /*
        ScheduledExecutorService 的主要作用就是可以将定时任务与线程池功能结合使用。
            1.使用 scheduleAtFixedRate() 方法实现周期性执行
            2.使用 Callable 延迟运行
            3.使用 scheduleWithFixedDelay() 方法实现周期性执行
        */

        //-----------------------------------------------------------------------------------

        /*
        * 使用 scheduleWithFixedDelay() 方法实现周期性执行
        * */
        //启动一个线程然后每1秒钟运行一次
//        ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
//        exec.scheduleWithFixedDelay(new Runnable()
//        {
//            public void run()
//            {
//                System.out.println(new Date());
//            }
//        }, 5, 1, TimeUnit.SECONDS); //initialDelay初始延迟、Delay延迟、单位(秒 SECONDS)
        /*
        scheduleWithFixedDelay 的3个参数:
                initialDelay初始延迟:启动一个新线程真正执行之前,所要延迟的时间
                Delay延迟:新线程每隔少时间单位执行1次
                时间单位:每次隔多少时间单位
        */

        //-----------------------------------------------------------------------------------

        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        System.out.println("X="+new Date());
        executorService.scheduleWithFixedDelay(new MyRunable(), 0, 2, TimeUnit.SECONDS);
        System.out.println("Y="+new Date());

        /*
        scheduleWithFixedDelay 的3个参数:
                initialDelay初始延迟:启动一个新线程真正执行之前,所要延迟的时间
                Delay延迟:新线程每隔少时间单位执行1次
                时间单位:每次隔多少时间单位
        */

        //-----------------------------------------------------------------------------------

        /*
         * 使用 scheduleAtFixedRate() 方法实现周期性执行
         * */
//        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
//        executorService.scheduleAtFixedRate(new Runnable()
//        {
//            @Override
//            public void run()
//            {
//                System.out.println(new Date());
//            }
//        }, 0, 1000, TimeUnit.MILLISECONDS);
        /*
        scheduleAtFixedRate 的3个参数:
                initialDelay初始延迟:启动一个新线程真正执行之前,所要延迟的时间
                Delay延迟:新线程每隔少时间单位执行1次
                时间单位:每次隔多少时间单位
        */
        //-----------------------------------------------------------------------------------

        /*
         * 使用 Callable 延迟运行
         * */

//        try {
//            List<Callable> callableList = new ArrayList<>();
//            callableList.add(new MyCallableA());
//            callableList.add(new MyCallableB());
//            ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
//
//            //schedule(Callable对象, 延迟时间, 延迟时间的单位)
//            ScheduledFuture futureA = executorService.schedule(callableList.get(0), 1, TimeUnit.SECONDS);
//            ScheduledFuture futureB = executorService.schedule(callableList.get(1), 4, TimeUnit.SECONDS);
//
            System.out.println("X = " + System.currentTimeMillis());
//            System.out.println("X = " + new Date());
//            System.out.println("返回值A:" + futureA.get()); //get() 调用 Callable对象对象中的 call()方法
//            System.out.println("Y = " + new Date());
//            System.out.println("返回值B:" + futureB.get());//get() 调用 Callable对象对象中的 call()方法
            System.out.println("Y = " + System.currentTimeMillis());
//            System.out.println("Y = " + new Date());
//
//            executorService.shutdown();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } catch (ExecutionException e) {
//            e.printStackTrace();
//        }
//
    }

    //-----------------------------------------------------------------------------------

    static class MyRunable implements Runnable {
        @Override
        public void run() {
            try {
                System.out.println( new Date());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    //-----------------------------------------------------------------------------------

//    static class MyCallableA implements Callable<String>
//    {
//        @Override
//        public String call() throws Exception
//        {
//            try
//            {
//                System.out.println("callA begin " + Thread.currentThread().getName() + ", " + System.currentTimeMillis());
                TimeUnit.SECONDS.sleep(3); // 休眠3秒
//                System.out.println("callA end " + Thread.currentThread().getName() + ", " + System.currentTimeMillis());
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            return "returnA";
//        }
//    }
//
//    static class MyCallableB implements Callable<String>
//    {
//        @Override
//        public String call() throws Exception
//        {
//            System.out.println("callB begin " + Thread.currentThread().getName() + ", " + System.currentTimeMillis());
//            System.out.println("callB end " + Thread.currentThread().getName() + ", " + System.currentTimeMillis());
//            return "returnB";
//        }
//    }
}

第二种方式:定时任务 执行,相当于创建多一个线程专门进行执行定时任务

 

Timer timer = new Timer();
timer.schedule(new TimerTask()
{
    public void run() {
        flagIndex = 1;
    }
}, 0 , 3600000); //delay延迟:延迟多少时间之后才进行第一次启动。period时期:表示每隔多长时间执行一次

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

あずにゃん

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值