Chapter 21

Digging Deeper into Concurrent Execution

Even in such a concise tutorial as this one, Java threads deserve two dedicated lessons. Let’s continue delving deeper into the world of multi-threaded applications.

Joining Threads

In Lesson 20 you learned that a thread can wait for a fixed period or for a notification on some event. Now let’s consider a scenario in which you need to start multiple threads and continue program execution only when all threads are complete. The Thread class has a method, join(), that you can use in this case.

Revisit the TestThreads3 program shown in Listing 20-9. If you run this program the system console will show the message “The main method of TestThreads3 is finished”; after that will it show the output of the portfolio and market news threads, which keep running for a while. If you want to make sure that the main method is waiting until the other two threads are finished, you can use the method join(), as shown in Listing 21-1.

download.eps

Listing 21-1: Joining threads

 public class TestThreadJoin {       public static void main(String args[]){            MarketNews3 mn = new MarketNews3("Market News");          mn.start();            Portfolio3 p = new Portfolio3("Portfolio data");          p.start();            try{               mn.join();               p.join();            }catch (InterruptedException e){               e.printStackTrace();          } ...

Get Java® Programming 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.