Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for a thread to finish before another thread starts in Java/Android?

Let's say I've got this very simple code:

for(int i = 0; i < 10; i++) { 
    thread = new Thread(this); 
    thread.start(); 
} 

However, in this code, the thread apparently starts 10 times at once and it doesn't wait before the previous one is finished. How do you check if the thread is finished before letting the thread start again?

like image 245
ZimZim Avatar asked Nov 27 '11 19:11

ZimZim


People also ask

How do I make a thread wait for another thread?

The wait() Method Simply put, calling wait() forces the current thread to wait until some other thread invokes notify() or notifyAll() on the same object. For this, the current thread must own the object's monitor.

Which method wait for a Java thread to finish?

The wait() and join() methods are used to pause the current thread. The wait() is used in with notify() and notifyAll() methods, but join() is used in Java to wait until one thread finishes its execution.

How do you wait for a runnable to finish?

Create an Object called lock . Then after runOnUiThread(myRunnable); , you can call lock. wait() .

How do you wait in a thread?

wait() causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0). The current thread must own this object's monitor.


2 Answers

Before answering your question, I strongly encourage you to look into ExecutorServices such as for instance the ThreadPoolExecutor.

Now to answer your question:

If you want to wait for the previous thread to finish, before you start the next, you add thread.join() in between:

for(int i = 0; i < 10; i++) { 
    thread = new Thread(this); 
    thread.start(); 

    thread.join();    // Wait for it to finish.
}

If you want to kick off 10 threads, let them do their work, and then continue, you join on them after the loop:

Thread[] threads = new Thread[10];
for(int i = 0; i < threads.length; i++) { 
    threads[i] = new Thread(this); 
    threads[i].start(); 
}

// Wait for all of the threads to finish.
for (Thread thread : threads)
    thread.join();
like image 132
aioobe Avatar answered Sep 29 '22 16:09

aioobe


If every thread must wait for the previous one to finish before starting, you'd better have one unique thread executing the original run method 10 times in sequence:

Runnable r = new Runnable() {
    public void run() {
        for (int i = 0; i < 10; i++) {
            OuterClass.this.run();
        }
    }
}
new Thread(r).start();
like image 41
JB Nizet Avatar answered Sep 28 '22 16:09

JB Nizet