Extending the Thread Class Implementing the Runnable Interface

J.E.D.I.

9.4.1 Extending the Thread Class

The next example is a user-defined Thread class that prints the name of a thread object for 100 times. class PrintNameThread extends Thread { PrintNameThreadString name { supername; start; runs the thread once instantiated } public void run { String name = 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; } } Observe that the reference variables pnt1, pnt2, pnt3, and pnt4 are simply used once. For this application, there is really no need to use variables to refer to each thread. You can replace the body of the main method with the following statements: new PrintNameThreadA; new PrintNameThreadB; new PrintNameThreadC; new PrintNameThreadD; The program produces different outputs for each run. Here is a sample output. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABCDABCDABCDABCDABCDABCDA BCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABC DABCDABCDABCDABCDABCDABCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBC DBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBCDBC DBCDBCDBCDBCDBCDBCDBCDBCD

9.4.2 Implementing the Runnable Interface

Another way of creating user-defined threads is to implement the Runnable interface. The only method that the Runnable interface requires you to implement is the run method. Think of the run method as the main method of the threads you create. The following example is similar to the last example you studies but uses the second way of creating threads instead. class PrintNameThread implements Runnable { Thread thread; PrintNameThreadString name { thread = new Threadthis, name; thread.start; Introduction to Programming II Page 124 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