Java wait all threads finished

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.

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

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 
#include

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.

Читайте также:  Php string to int error

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

Источник

Java – Waiting for Running Threads to Finish

Java concurrency allows running multiple sub-tasks of a task in separate threads. Sometimes, it is necessary to wait until all the threads have finished their execution. In this tutorial, we will learn a few ways to make the current thread wait for the other threads to finish.

Читайте также:  Java swing scroll jpanel

1. Using ExecutorService and Future.get()

Java ExecutorService (or ThreadPoolExecutor) helps execute Runnable or Callable tasks asynchronously. Its submit() method returns a Future object that we can use to cancel execution and/or wait for completion.

In following example, we have a demo Runnable task. Each task completes in a random time between 0 to 1 second.

public class DemoRunnable implements Runnable < private Integer jobNum; public DemoRunnable(Integer index) < this.jobNum = index; >@SneakyThrows @Override public void run() < Thread.sleep(new Random(0).nextLong(1000)); System.out.println("DemoRunnable completed for index : " + jobNum); >>

We are submitting 10 tasks to the executor service. And then, we invoke Future.get() method on each Future object as received after submitting the task to the executor. The Future.get() waits if necessary for the task to complete, and then retrieves its result.

ExecutorService executor = Executors.newFixedThreadPool(5); List> futures = new ArrayList<>(); for (int i = 1; i f = executor.submit(new DemoRunnable(i)); futures.add(f); > System.out.println("###### All tasks are submitted."); for (Future f : futures) < f.get(); >System.out.println("###### All tasks are completed.");
###### All tasks are submitted. DemoRunnable completed for index : 3 DemoRunnable completed for index : 4 DemoRunnable completed for index : 1 DemoRunnable completed for index : 5 DemoRunnable completed for index : 2 DemoRunnable completed for index : 6 DemoRunnable completed for index : 10 DemoRunnable completed for index : 7 DemoRunnable completed for index : 9 DemoRunnable completed for index : 8 ###### All tasks are completed.

Note that the wait may terminate earlier under the following conditions:

  • the task is cancelled
  • the task execution threw an exception
  • there is an InterruptedException i.e., current thread was interrupted while waiting.

In such a case, we should implement our own logic to handle the exception.

2. Using ExecutorService shutdown() and awaitTermination()

The awaitTermination() method blocks until all tasks have completed execution after a shutdown() request on the executor service. Similar to Future.get(), it can unblock earlier if the timeout occurs, or the current thread is interrupted.

The shutdown() method closes the executor so no new tasks can be submitted, but previously submitted tasks continue execution.

The following method has the complete logic of waiting for all tasks to finish in 1 minute. After that, the executor service will be shut down forcibly using shutdownNow() method.

void shutdownAndAwaitTermination(ExecutorService executorService) < executorService.shutdown(); try < if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) < executorService.shutdownNow(); >> catch (InterruptedException ie) < executorService.shutdownNow(); Thread.currentThread().interrupt(); >>

We can use this method as follows:

ExecutorService executor = Executors.newFixedThreadPool(5); for (int i = 1; i System.out.println("###### All tasks are submitted."); shutdownAndAwaitTermination(executor); System.out.println("###### All tasks are completed.");

3. Using ExecutorService invokeAll()

This approach can be seen as a combination of the previous two approaches. It accepts the tasks as a collection and returns a list of Future objects to retrieve output if necessary. Also, it uses the shutdown and awaits logic for waiting for the tasks to be complete.

In following example, we are using the DemoCallable class that is very similar to DemoRunnable, except it returns an Integer value.

ExecutorService executor = Executors.newFixedThreadPool(10); List tasks = Arrays.asList( new DemoCallable(1), new DemoCallable(2), new DemoCallable(3), new DemoCallable(4), new DemoCallable(5), new DemoCallable(6), new DemoCallable(7), new DemoCallable(8), new DemoCallable(9), new DemoCallable(10)); System.out.println("###### Submitting all tasks."); List> listOfFutures = executor.invokeAll(tasks); shutdownAndAwaitTermination(executor); System.out.println("###### All tasks are completed.");

Note that listOfFutures stores the task outputs in the same order in which we had submitted the tasks to the executor service.

for (Future f : listOfFutures) < System.out.print(f.get() + " "); //Prints 1 2 3 4 5 6 7 8 9 10 >

The CountDownLatch class enables a Java thread to wait until a collection of threads (latch is waiting for) to complete their tasks.

CountDownLatch works by having a counter initialized with a number of threads, which is decremented each time a thread completes its execution. When the count reaches zero, it means all threads have completed their execution, and the main thread waiting on the latch resumes the execution.

In the following example, the main thread is waiting for 3 given services to complete before reporting the final system status. We can read the whole example in CountDownLatch example.

CountDownLatch latch = new CountDownLatch(3); List services = new ArrayList<>(); services.add(new NetworkHealthChecker(latch)); services.add(new CacheHealthChecker(latch)); services.add(new DatabaseHealthChecker(latch)); Executor executor = Executors.newFixedThreadPool(services.size()); for(final BaseHealthChecker s : services) < executor.execute(s); >//Now wait till all health checks are complete latch.await();

In this tutorial, we learned to make an application thread wait for other threads to finish. We learned to use the ExecutorService methods and CountDownLatch class.

Источник

Оцените статью