如何以排定的速度运行任务,而不必等待任务完成呢?

时间:2018-12-31 12:37:40

标签: java concurrency scheduledexecutorservice

当前,我有一些代码需要每33毫秒运行一次。但是,我要调用的操作大约需要270ms。有什么办法可以安排我的任务,使其无论之前执行的任务如何都可以运行?

我尝试实现ScheduledExecutorService变量,并在“ ScheduledFixedRate”上运行任务,但是当前正在等待任务。

Runnable imageCapture = new Runnable() {

        public void run() {
            // code that takes approximately 270ms
        }
    };

executor = Executors.newScheduledThreadPool(4);
executor.scheduleAtFixedRate(imageCapture, 0, 33, TimeUnit.MILLISECONDS);

1 个答案:

答案 0 :(得分:0)

将任务分成两部分:一个进行实际计算,另一个定期执行并启动第一个:

executor = Executors.newScheduledThreadPool(4);

Runnable imageCapture = new Runnable() {

    public void run() {
        // code that takes approximately 270ms
    }
};

Runnable launcher = new Runnable() {

    public void run() {
        executor.execute(imageCapture);
    }
};

executor.scheduleAtFixedRate(launcher, 0, 33, TimeUnit.MILLISECONDS);