-1

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. 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.

Can please help on this?

  • 1
    I'm not quite sure I understand the question completely. Is it a list of tasks or a list of items that a single task could work on? If the latter then why don't you just pass the list of items to whatever is used to execute the task? Where does the "at some interval" come in except for the requirement of serial execution? Also "This list is being used by multiple threads." - how is this related to the question? This might actually be a different story, i.e. related to access synchronization or completion. – Thomas Nov 08 '21 at 10:28

1 Answers1

0

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();
Arthur Klezovich
  • 2,595
  • 1
  • 13
  • 17