如何执行可调用的固定次数,并且每次执行之间有一个睡眠间隔/延迟

1 java concurrency multithreading executorservice

我有一种情况,我需要检查是否满足特定条件,并且需要在声明不满足条件之前定期执行一定次数以检查条件,并且每次执行之间都需要延迟/睡眠间隔。

代码结构:

class checkCondition<T> implements Callable<T>{
 @Override
public T call() {
//Do Stuff and return result
return result;
}
public class TaskRunner<T> {
private final ExecutorService executor = Executors.newSingleThreadExecutor();
public Future<T> runTask(checkCondiiton task, int times, long sleep){

while(times > 0){
future = executor.submit(task);
Thread.sleep(sleep);
times--;
}
return future;
}
}

}
Run Code Online (Sandbox Code Playgroud)

上面的实现正确吗?如果没有,请建议哪种方法更好。我是ExecutorService和Java Concurrency的新手。

Maa*_*aas 5

尝试使用Executors.newSingleThreadScheduledExecutor()

例:

public class FixedScheduledExcutor
{
    public static void main(String[] args) throws InterruptedException
    {
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        CountDownLatch latch = new CountDownLatch(5);
        executorService.scheduleAtFixedRate(new MyRunner(latch), 5, 5, TimeUnit.SECONDS);
        latch.await();
        System.out.println("Shutting down service...");
        executorService.shutdown();
    }
}

class MyRunner implements Runnable
{
    CountDownLatch latch;

    MyRunner(CountDownLatch latch)
    {
        this.latch = latch;
    }

    @Override
    public void run()
    {
        System.out.println("Do something : " + latch.getCount());
        latch.countDown();
    }
}
Run Code Online (Sandbox Code Playgroud)