简体   繁体   English

运行两次后停止ScheduledExecutorService吗?

[英]Stop ScheduledExecutorService after it runs two times?

I'm trying to have some code to be executed only 2 times with a delay of 500 microseconds between each execution. 我试图让某些代码仅执行两次,每次执行之间延迟500微秒。

So far I have used the ScheduledExecutorService and an int counter to track how may times the ExecutorService has run my code, but I want know if this is a good approach and if there is better way: 到目前为止,我已经使用ScheduledExecutorService和一个int counter来跟踪ExecutorService运行我的代码的时间,但是我想知道这是否是一种好方法以及是否有更好的方法:

private void dingdong() {

    ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
    exec.scheduleAtFixedRate(new Runnable() {
        int count;

        @Override
        public void run() {
            count++;

            //TODO operation

            if (count == 2) {
                exec.shutdownNow();
            }
        }
    }, 0, 500, TimeUnit.MICROSECONDS);

}

I think the ExecutorService is overkill. 我认为ExecutorService过于矫ExecutorService正。 If you just use a normal Thread, it can run your operation, sleep, and run it again. 如果仅使用普通线程,则该线程可以运行,休眠并再次运行。

new Thread(() -> {
    doTheThing();
    TimeUnit.MICROSECONDS.sleep(500);
    doTheThing();
}).start();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM