Extending vs. Implementing An Example Using the join Method

J.E.D.I. } public void run { String name = thread.getName; for int i = 0; i 100; i++ { System.out.printname; } } } class TestThread { public static void mainString args[] { new PrintNameThreadA; new PrintNameThreadB; new PrintNameThreadC; new PrintNameThreadD; } }

9.4.3 Extending vs. Implementing

Of the two ways of creating threads, choosing between these two is a matter of taste. Implementing the Runnable interface may take more work since we still have to declare a Thread object and call the Thread methods on this object. Extending the Thread class, however, would mean that your class can no longer extend any other class since Java prohibits multiple inheritance. A trade-off between ease of implementation and possibility of extending the class is made with the style you selected. Weigh out which is more important to you because the choice is yours. Introduction to Programming II Page 125 J.E.D.I.

9.4.4 An Example Using the join Method

Now that youve learned how to create threads, lets see how the join method works. The example below uses the version of the join method without any argument. As a review, the method when called with no argument causes the currently running thread to wait until the thread that calls this method finishes execution. class PrintNameThread implements Runnable { Thread thread; PrintNameThreadString name { thread = new Threadthis, name; thread.start; } public void run { String name = thread.getName; for int i = 0; i 100; i++ { System.out.printname; } } } class TestThread { public static void mainString args[] { PrintNameThread pnt1 = new PrintNameThreadA; PrintNameThread pnt2 = new PrintNameThreadB; PrintNameThread pnt3 = new PrintNameThreadC; PrintNameThread pnt4 = new PrintNameThreadD; System.out.printlnRunning threads...; try { pnt1.thread.join; pnt2.thread.join; pnt3.thread.join; pnt4.thread.join; } catch InterruptedException ie { } System.out.println\nThreads killed.; printed last } } Try running this program yourself. What have you noticed? Through the join method calls, we are assured that the last statement is executed at the last part. Here is a sample output of running the code: Running threads... AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBCDBCD BCDBCDBCBCBCBCBCBCDBDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCCCCC Threads killed. Now, comment out the try-catch block where the join method was invoked. Is there any difference in the program output? Introduction to Programming II Page 126 J.E.D.I.

9.5 Synchronization