Java Wait for Thread to Finish

Java Wait for thread to finish

Thread has a method that does that for you join which will block until the thread has finished executing.

How do I make the current thread wait for another thread to finish before proceeding?

If you want to block your current thread until the other thread finishes its task, maybe doing the task on a separate thread is actually pointless, you are not achieving any parallelism.

Your Task isn't even returning anything, so there is even no other reason to block until a result from the second thread is returned.

If you still want to execute it in parallel and block waiting for the task to finish, you could use this:

System.out.println("Thread: " + Thread.currentThread());
Thread thread = new Thread(() -> {
System.out.println("Thread: " + Thread.currentThread());
updateData();
updateSwingGUI();
}).start();

System.out.println("I'm on the old thread, can do something in parallel.");

thread.join();
System.out.println("Second thread finished updating GUI.");

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

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

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

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.


Related Topics



Leave a reply



Submit