ScheduledThreadPoolExecutor周期性执行线程任务scheduleAtFixedRate

ScheduledThreadPoolExecutor周期性执行线程任务scheduleAtFixedRate

        ScheduledThreadPoolExecutor mScheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
        mScheduledThreadPoolExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程id:" + Thread.currentThread().getId() + "\t" + System.currentTimeMillis());
            }
        }, 0, 3, TimeUnit.SECONDS);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(12);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("关闭ScheduledThreadPoolExecutor");
                mScheduledThreadPoolExecutor.shutdown();
            }
        }).start();

ScheduledThreadPoolExecutor每隔3秒周期性的在线程中打印当前时间。同时另起一个线程,12秒后关闭ScheduledThreadPoolExecutor。

输出:

06-19 15:55:41.469 27469-27499/zhangphil.test I/System.out: 线程id:12150	1529394941469
06-19 15:55:44.467 27469-27499/zhangphil.test I/System.out: 线程id:12150	1529394944467
06-19 15:55:47.467 27469-27499/zhangphil.test I/System.out: 线程id:12150	1529394947467
06-19 15:55:50.468 27469-27499/zhangphil.test I/System.out: 线程id:12150	1529394950467
06-19 15:55:53.466 27469-27499/zhangphil.test I/System.out: 线程id:12150	1529394953466
06-19 15:55:53.468 27469-27500/zhangphil.test I/System.out: 关闭ScheduledThreadPoolExecutor

你可能感兴趣的:(Java,Java多线程,Java)