ScheduledExecutorService的使用及守护线程

只运行一次

https://img-blog.csdnimg.cn/20201028113139387.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dhbmd4dWVsZWkwMzY=,size_16,color_FFFFFF,t_70

private static ScheduledExecutorService scheduler;

    public static void main(String[] args) throws Exception {

        scheduler = Executors.newScheduledThreadPool(5);

        // 循环任务,按照上一次任务的发起时间计算下一次任务的开始时间

        scheduler.scheduleAtFixedRate(((

                        new Runnable() {

                            @Override

                            public void run() {

                                System.out.println(

                                        " 开始 threadId = "

                                                + Thread.currentThread().getId()

                                                + ",,,threadName = " + Thread.currentThread().getName()

                                                + ",,,时间" +  formatDateToString(new Date())

                                );

                                try {

                                    Thread.sleep(3000);

                                    System.out.println(

                                            " 结束 threadId = "

                                                    + Thread.currentThread().getId()

                                                    + ",,,threadName = " + Thread.currentThread().getName()

                                                    + ",,,时间" + formatDateToString(new Date())

                                    );

                                } catch (InterruptedException e) {

                                    e.printStackTrace();

                                }

                                //模拟抛出异常

                                if (1 == 1) {

                                    throw new RuntimeException("异常");

                                }

                            }

                        })),

                0, 1,

                TimeUnit.SECONDS);

        Thread.sleep(20000);

        System.out.println(

                " 主线程 threadId = "

                        + Thread.currentThread().getId()

                        + ",,,threadName = " + Thread.currentThread().getName()

                        + ",,,时间" + formatDateToString(new Date())

        );

    }

    public static String formatDateToString(Date time) {

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

        return sdf.format(time);

}

https://img-blog.csdnimg.cn/20201028111403823.png

private static ScheduledExecutorService scheduler;

    public static void main(String[] args) throws Exception {

        scheduler = Executors.newScheduledThreadPool(5);

        // 循环任务,按照上一次任务的发起时间计算下一次任务的开始时间

        scheduler.scheduleAtFixedRate(((

                        new Runnable() {

                            @Override

                            public void run() {

                                System.out.println(

                                        " 开始 threadId = "

                                                + Thread.currentThread().getId()

                                                + ",,,threadName = " + Thread.currentThread().getName()

                                                + ",,,时间" +  formatDateToString(new Date())

                                );

                                try {

                                    Thread.sleep(3000);

                                    System.out.println(

                                            " 结束 threadId = "

                                                    + Thread.currentThread().getId()

                                                    + ",,,threadName = " + Thread.currentThread().getName()

                                                    + ",,,时间" + formatDateToString(new Date())

                                    );

                                } catch (InterruptedException e) {

                                    e.printStackTrace();

                                }

                            }

                        })),

                0, 1,

                TimeUnit.SECONDS);

    }

    public static String formatDateToString(Date time) {

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

        return sdf.format(time);

}

可以看到其实间隔时间已经变成了 任务执行时间来控制,但是一般来说,很少有任务执行时间超过间隔时间,但是这个知识点还是要知道。 

https://img-blog.csdnimg.cn/20201028111720513.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dhbmd4dWVsZWkwMzY=,size_16,color_FFFFFF,t_70

scheduleAtFixedRate 正常使用 延迟时间1S,执行任务时间 1S,间隔时间3S

private static ScheduledExecutorService scheduler;

    public static void main(String[] args) throws Exception {

        scheduler = Executors.newScheduledThreadPool(5);

        // 循环任务,按照上一次任务的发起时间计算下一次任务的开始时间

        scheduler.scheduleAtFixedRate(((

                        new Runnable() {

                            @Override

                            public void run() {

                                System.out.println(

                                        " 开始 threadId = "

                                                + Thread.currentThread().getId()

                                                + ",,,threadName = " + Thread.currentThread().getName()

                                                + ",,,时间" +  formatDateToString(new Date())

                                );

                                try {

                                    Thread.sleep(1000);

                                    System.out.println(

                                            " 结束 threadId = "

                                                    + Thread.currentThread().getId()

                                                    + ",,,threadName = " + Thread.currentThread().getName()

                                                    + ",,,时间" + formatDateToString(new Date())

                                    );

                                } catch (InterruptedException e) {

                                    e.printStackTrace();

                                }

                            }

                        })),

                0, 3,

                TimeUnit.SECONDS);

    }

    public static String formatDateToString(Date time) {

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

        return sdf.format(time);

}

scheduleWithFixedDelay 正常使用

private static ScheduledExecutorService scheduler;

    public static void main(String[] args) throws Exception {

        scheduler = Executors.newScheduledThreadPool(5);

        // 循环任务,按照上一次任务的发起时间计算下一次任务的开始时间

        scheduler.scheduleWithFixedDelay(((

                        new Runnable() {

                            @Override

                            public void run() {

                                System.out.println(

                                        " 开始 threadId = "

                                                + Thread.currentThread().getId()

                                                + ",,,threadName = " + Thread.currentThread().getName()

                                                + ",,,时间" +  formatDateToString(new Date())

                                );

                                try {

                                    Thread.sleep(3000);

                                    System.out.println(

                                            " 结束 threadId = "

                                                    + Thread.currentThread().getId()

                                                    + ",,,threadName = " + Thread.currentThread().getName()

                                                    + ",,,时间" + formatDateToString(new Date())

                                    );

                                } catch (InterruptedException e) {

                                    e.printStackTrace();

                                }

                            }

                        })),

                0, 1,

                TimeUnit.SECONDS);

    }

    public static String formatDateToString(Date time) {

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

        return sdf.format(time);

}

scheduleWithFixedDelay以上一次任务的结束时间 + 延迟时间 = 下一次任务的开始时间。

https://img-blog.csdnimg.cn/20201028112216360.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dhbmd4dWVsZWkwMzY=,size_16,color_FFFFFF,t_70

以上就是两个循环任务的使用

private static ScheduledExecutorService scheduler;

    public static void main(String[] args) throws Exception {

        scheduler = Executors.newScheduledThreadPool(5, new ThreadFactory() {

            private AtomicInteger counter = new AtomicInteger(0);

            //可以在这里对线程做一些操作

            @Override

            public Thread newThread(Runnable r) {

                int count = counter.incrementAndGet();

                System.out.println("线程创建counter = " + count);

                Thread thread = new Thread(r);

                thread.setName("测试线程"+count);

                return thread;

            }

        });

        System.out.println("main thread time : " + formatDateToString(new Date()));

        // 循环任务,按照上一次任务的发起时间计算下一次任务的开始时间

        scheduler.scheduleAtFixedRate(((

                        new Runnable() {

                            @Override

                            public void run() {

                                System.out.println(

                                        " 开始 threadId = "

                                                + Thread.currentThread().getId()

                                                + ",,,threadName = " + Thread.currentThread().getName()

                                                + ",,,时间" +  formatDateToString(new Date())

                                );

                            }

                        })),

                1,5,

                TimeUnit.SECONDS);

    }

    public static String formatDateToString(Date time) {

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

        return sdf.format(time);

}

其实就是提供了一个扩展点,允许你在创建线程的时候,做一些管理或者说一些其他的操作

https://img-blog.csdnimg.cn/20201028114539843.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dhbmd4dWVsZWkwMzY=,size_16,color_FFFFFF,t_70

也可以使用 ThreadFactoryBuilder 构建类 来构建FactoryBuilder

scheduler = Executors.newScheduledThreadPool(5,new ThreadFactoryBuilder()

                .setNameFormat("测试线程-%d")

//                .setDaemon(true) //这个参数是设置为守护线程 也叫 服务线程

                .build());

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值