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

Exception or error:

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?

How to solve:

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

###

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

###

Just to elaborate on aioobe’s suggestion:

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

There is a particular ExecutorService that can be used for this task:

ExecutorService pool = Executors.newSingleThreadExecutor();
for (int i=0; i<10; i++) {
  pool.submit(this); //assuming this is a Runnable
}
pool.shutdown(); //no more tasks can be submitted, running tasks are not interrupted

newSingleThreadExecutor() is similar to calling newFixedThreadPool(1) but ensures that the service cannot be reconfigured to use more than one thread.

Leave a Reply

Your email address will not be published. Required fields are marked *