Thursday, 13th October 2011
Follow WikiJava on twitter now. @Wikijava

Starting many Threads and waiting for them to finish

From WikiJava

Jump to: navigation, search
The author suggests:

buy this book

This article shows you how to start several threads and how to wait them to finish.

Contents

When can I use this?

I use this when I need to wait for several threads to be run. For example when I don't want to exit from the main program until all the processes have completed.

how does it work

We use two for loops, the first builds the java.lang.Thread objects, run them and adds them to a java.util.List of Threads.

After the for loop exits all the threads are running and stored in the List.

If we don't wait for them to finish the program would just execute the next commands and eventually exit.

We don't want it to continue and in this case we want to wait all the threads to be complete.

Here comes the second for loop. Which iterates through each thread in the List and uses the method join with signature:

void java.lang.Thread.join() throws InterruptedException

Which stops the execution until the process dies.

The second for loop exits only if all the processes in the list are dead. It stops the execution of the thread containing it until they all die.

Creating the List of Threads

The List<Thread> threads contains all the started threads. The requests field contains a List of Request objects which implements the interface Runnable.

In the for the Threads are created, then added to the List, then started.

// start each request and add it to the thread list
	List<Thread> threads = new ArrayList<Thread>();
	for (Request currentRequest : this.requests) {
	    Thread curThread = new Thread(currentRequest);
	    threads.add(curThread);
	    curThread.start();
	    log.info("Started request " + currentRequest.getUrl()
		    + " on thread " + curThread.getName());
	}

Waiting for the threads to end

To wait for each Thread to finish its execution we use the join method, which blocks until the Thread it's called on ends.

If we call join on a thread that is already dead, the method returns immediately.

// wait for all the threads to be completed
	for (Thread curThread : threads) {
	    try {
		// starting from the first wait for each one to finish.
		curThread.join();
	    } catch (InterruptedException e) {
		throw new BatBotException(e);
	    }
	}

Join throws an InterruptedException if the wait was ended because of some reason. This can be useful to check if the Thread completed its calculations or it was stopped before.

the run Requests Method

Image:250px-Subversion.png
You can download the complete code of this article from the Subversion repository at this link

Using the username:readonly and password: readonly

See the using the SVN repository instructions page for more help about this.
   /**
     * 
     * executes the http requests listed in the requests List
     * 
     * @throws BatBotException
     */
    public void runRequests() throws BatBotException {
	log.entering("BatBot", "executeRequests");
	// start each request and add it to the thread list
	List<Thread> threads = new ArrayList<Thread>();
	for (Request currentRequest : this.requests) {
	    Thread curThread = new Thread(currentRequest);
	    threads.add(curThread);
	    curThread.start();
	    log.info("Started request " + currentRequest.getUrl()
		    + " on thread " + curThread.getName());
	}
 
	// wait for all the threads to be completed
	for (Thread curThread : threads) {
	    try {
		// starting from the first wait for each one to finish.
		curThread.join();
	    } catch (InterruptedException e) {
		throw new BatBotException(e);
	    }
	}
 
	log.exiting("BatBot", "executeRequests");
    }

Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page


Comments on wikijava are disabled now, cause excessive spam.