Home > Net >  How to start next thread when any one of 5 set of threads is stopped?
How to start next thread when any one of 5 set of threads is stopped?

Time:10-12

I am creating program to run a logic in parallel with help of thread. The logic has to be done in a loop of a list and that list may contain 1000 rows to process , so i started each thread in a loop and once thread size reaches 5, i will call thread.join for all the 5 started thread. So i think that this will start the 2nd set of 5 threads only after the first set of 5 threads are completed? is my understanding correct? i am kind of new to threads.

So my need is to start the 6th thread when any one of the previous set of 5 threads in completed. or start 6th and 7th when any 2 in the previous set of threads are completed.

My code

public static void executeTest(){
         for (int i = 0; i < rows1; i  ) {
                    RunnableInterface task = new New RunnableInterface(params);
                    Thread thread = new Thread(task);
                    thread.start();
                    threads.add(thread);
                    if ((threads.size() % 5 == 0) || ((i == rows1-1) && (threads.size() < 5))) {
                        waitForThreads(threads);
                    }
                }
}
    private static void waitForThreads(List<Thread> threads) {
            for (Thread thread : threads) {
                try {
                    thread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            threads.clear();
        }

What kind of modification do i need to do to achieve above mentioned results

CodePudding user response:

You can use an ExecutorService with unbounded input queue and fixed number of threads like this:

ExecutorService exec = Executors.newFixedThreadPool(5);
// As many times as needed:
for(int i = 0; i< 100_000; i  ) {
    Runnable myrunnable = () -> {}; // new RunnableInterface(params)
    exec.submit(myrunnable);
}
exec.shutdown();
exec.awaitTermination(1, TimeUnit.DAYS);

In JDK19 the executor service is AutoClosable, so you can simplify to:

try (ExecutorService exec = Executors.newFixedThreadPool(5)) {
   ...
}
  • Related