How to Wait for a Number of Threads to Complete

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.

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();
}

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()

How to wait till all threads finish their work?

Your last threading example is close, but you have to collect the threads in a list, start them all at once, then wait for them to complete all at once. Here's a simplified example:

import threading
import time

# Lock to serialize console output
output = threading.Lock()

def threadfunc(a,b):
for i in range(a,b):
time.sleep(.01) # sleep to make the "work" take longer
with output:
print(i)

# Collect the threads
threads = []
for i in range(10,100,10):
# Create 9 threads counting 10-19, 20-29, ... 90-99.
thread = threading.Thread(target=threadfunc,args=(i,i+10))
threads.append(thread)

# Start them all
for thread in threads:
thread.start()

# Wait for all to complete
for thread in threads:
thread.join()

How to wait for all threads to complete

You need to protect the modification and reading of clientCount via synchronized. The main issue is that clientCount-- and clientCount++ are NOT an atomic operation and therefore two threads could execute clientCount-- / clientCount++ and end up with the wrong result.

Simply using volatile as you do above would ONLY work if ALL operations on the field were atomic. Since they are not, you need to use some locking mechanism. As Anton states, AtomicInteger is an excellent choice here. Note that it should be either final or volatile to ensure it is not thread-local.

That being said, the general rule post Java 1.5 is to use a ExecutorService instead of Threads. Using this in conjuction with Guava's Futures class could make waiting for all to complete to be as simple as:

Future<List<?>> future = Futures.successfulAsList(myFutureList);
future.get();
// all processes are complete

Futures.successfulAsList

make main thread wait for other threads to finish

You need to put the following line in the catch block:

Thread.currentThread().interrupt();

Also, you do not need the following lines:

if (Thread.currentThread().isInterrupted()) {
break;
}

Demo:

public class Switch implements Runnable {
private static boolean isOn;
private String name;
private static final Object lockedObject = new Object();

public Switch(String name) {
this.name = name;
}

public void toggle() {
System.out.println(name + ": " + isOn);
synchronized (lockedObject) {
isOn = !isOn;
}
}

@Override
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();// Add this line
break;
}
synchronized (lockedObject) {
toggle();
}
}
}

public static void main(String[] args) throws InterruptedException {
Switch switch1 = new Switch("switch1");
Switch switch2 = new Switch("switch2");
Thread thread1 = new Thread(switch1);
Thread thread2 = new Thread(switch2);
thread1.start();
thread2.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread1.interrupt();
thread2.interrupt();
}
}

How to make main thread wait for all child threads finish?

int main()
{
pthread_t tid[2];
for (int i = 0; i < 2; i++) {
pthread_create(&tid[i], NULL, routine, NULL);
}
for (int i = 0; i < 2; i++)
pthread_join(tid[i], NULL);
return 0;
}


Related Topics



Leave a reply



Submit