Wait Until All Threads Finish Their Work in Java

wait until all threads finish their work in java

The approach I take is to use an ExecutorService to manage pools of threads.

ExecutorService es = Executors.newCachedThreadPool();
for(int i=0;i<5;i++)
es.execute(new Runnable() { /* your task */ });
es.shutdown();
boolean finished = es.awaitTermination(1, TimeUnit.MINUTES);
// all tasks have finished or the time has been reached.

Java wait for all threads to complete before printing some information

Use a CountDownLatch: initialize it with the number of threads, then have each thread count down the latch when it's done. The main thread awaits the latch.

Something like this:

CountDownLatch latch = new CountDownLatch(args.length);
for (int i = 1; i < args.length; i++){
String filename = args[i];
new processFile(latch, filename, counter).start();
}

latch.await();
System.out.print(counter.numerOfMatches)

Each of your threads needs to see the latch, for example by passing it in the constructor. When the thread is done, it notifies / counts down the latch.

@Override
public void run() {
// do actual work, then signal we're done:
latch.countDown();
}

How to wait for a number of threads to complete?

You put all threads in an array, start them all, and then have a loop

for(i = 0; i < threads.length; i++)
threads[i].join();

Each join will block until the respective thread has completed. Threads may complete in a different order than you joining them, but that's not a problem: when the loop exits, all threads are completed.

WaitForMultipleObjects doesnt wait until all threads finish

This is the code you want:

#include <Windows.h>
#include <stdio.h>

DWORD IDs[5];

DWORD __stdcall ThreadProc(DWORD* TID) {
//expected this block to run infinitely.
while (1) {
printf("Inside Thread: %d. \n", *TID);
Sleep(1000);
}

return 0;
}

#define NBOFTHREADS 5

int main() {
HANDLE lpHandles[NBOFTHREADS];

for (int i = 0; i < NBOFTHREADS; i++) {
HANDLE Threadhandle = CreateThread(0, 0, ThreadProc, &IDs[i], 0, &IDs[i]);
printf("Thread %d -> ID %d started. \n", i, IDs[i]);
lpHandles[i] = Threadhandle;
}

WaitForMultipleObjects(NBOFTHREADS, lpHandles,TRUE, INFINITE);
return 0;
}

In your code you pass the pointer to ThreadId to the thread, but ThreadId is being overwritten upon the creation of each thread, therefore all threads are displaying the same thread id.

You can simplify the code above by using GetCurrentThreadId and not care about pasing the thread IDs to the thread.

DWORD __stdcall ThreadProc(void *unused) {
//expected this block to run infinitely.
while (1) {
printf("Inside Thread: %d. \n", GetCurrentThreadId());
Sleep(1000);
}

return 0;
}
...
HANDLE Threadhandle = CreateThread(0, 0, ThreadProc, NULL, 0, &IDs[i]);

How to let a thread wait until task is finished?

I don't think you need all that signaling between threads. You can just use thread.join

Also, one minor design flaw is that you have the threads in an infinite spin loop until the computation member is set. This will slow your initial performance a bit. You should set the computation member BEFORE starting the thread. That is, don't let the constructor of ComputationThread invoke thread.start. Do that in your compute function.

This is likely what you seek:

public static void compute(ComputationMethod method){
for(ComputationThread t:threads){
t.computation = method;
t.start();
}

// wait for all threads to finish
for(ComputationThread t:threads){
t.join();
}
}

Then your run function is simplified to:

public void run(){

try {
while(computation.execute()){}
}
catch (Exception e){
e.printStackTrace();
}
}

Java Multithreading wait for threads to finish

Add calls to join() at the end of run. the join() method waits for a thread to finish.

try
{
one.join();
two.join();
three.join();
four.join();
}
catch (InterruptedException e)
{
System.out.println("Interrupt Occurred");
e.printStackTrace();
}

And if you want to ignore interrupts (probably should at least figure out why it was interrupted but this will work)

boolean done = false;
while (!done)
{
try
{
one.join();
two.join();
three.join();
four.join();
done = true;
}
catch (InterruptedException e)
{
// Handle interrupt determine if need to exit.
}
}

https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join()



Related Topics



Leave a reply



Submit