简体   繁体   English

如何在Java中以某个时间间隔一个一个地执行列表中的项目?

[英]How to execute items in a list one by one at some interval in Java?

I have a List of Items.我有一个项目清单。 I want to run some operation for each item in the list one by one.我想对列表中的每个项目一一运行一些操作。 The operation might take 5 minutes to complete.该操作可能需要 5 分钟才能完成。 The ask is that for a particular item in the list the operation should start and complete then only the operation should start for the next item and so on.问题是对于列表中的特定项目,操作应该开始并完成,然后只有下一个项目的操作才应该开始,依此类推。 The operation should execute for only the number of items in the list.该操作应该只对列表中的项目数执行。

This list is being used by multiple threads.此列表正被多个线程使用。

I am thinking of using TimerTask for it or Schedular.我正在考虑使用 TimerTask 或 Schedular。

Can please help on this?可以请帮忙吗?

Ideally you should do it sequentially, since there is no benefit to using concurrency here.理想情况下,您应该按顺序进行,因为在这里使用并发没有任何好处。

However, if it needs to be multithreaded you can do something like ...但是,如果它需要多线程,您可以执行以下操作...

List<Runnable> tasks = new ArrayList<>();
tasks.add(new ThreadOne()); /* Pick better names for tasks */
tasks.add(new ThreadTwo());
...
ExecutorService worker = Executors.newSingleThreadExecutor();
worker.submit(() -> {
    while (!Thread.interrupted()) 
        tasks.forEach(Runnable::run);
});
worker.shutdown();

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

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