Starting many Threads and waiting for them to finishFrom WikiJavabuy this book
This article shows you how to start several threads and how to wait them to finish.
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 workWe use two After the 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 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 ThreadsThe 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 endTo wait for each Thread to finish its execution we use the 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); } }
the run Requests Method
/** * * 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"); } |
