18.2 THE RUNNABLE INTERFACE IN JAVA


18.2 THE RUNNABLE INTERFACE IN JAVA

It is not always possible to extend Thread to create a user-defined multithreadable class. What if your user-defined class already extends some other class? To get around this difficulty, Java also allows us to create a multithreadable class by directly implementing the Runnable interface, as we show in this section.[5]

The following version of the HelloThread class implements the Runnable interface by providing an implementation for run, the only method that is declared in the interface. In main, Runnable objects of type HelloThread are then passed to the Thread constructor for the creation of threads:

 
//ThreadBasicWithRunnable.java class HelloThread implements Runnable { String message; HelloThread( String message ) { this.message = message; } public void run() { //(A) //int sleeptime = (int) ( Math.random() * 3000 ); //(B) //try { //(C) // Thread.sleep( sleeptime ); //(D) //} catch( InterruptedException e ){} //(E) System.out.print( message ); } public static void main( String[] args ) { HelloThread ht1 = new HelloThread( "Good" ); //(F) Thread t1 = new Thread( ht1 ); //(G) HelloThread ht2 = new HelloThread( " morning" ); Thread t2 = new Thread( ht2 ); HelloThread ht3 = new HelloThread( " to" ); Thread t3 = new Thread( ht3 ); t1.start(); //(H) t2.start(); t3.start(); try { Thread.sleep( 1000 ); //(I) } catch( InterruptedException e ){} System.out.println( " you!" ); } }

The implementation of the run method in line (A) is the same as before, except that (if you uncomment the commented out part) you must now invoke Thread.sleep in line (D), as opposed to just sleep, since HelloThread does not inherit from Thread any longer.

One of the main differences between the code of the previous section and the code shown here is in how main is set up. For our first thread, we construct in line (F) a HelloThread object ht1. We then pass ht1 as an argument to the Thread constructor in line (G). This allows us to invoke the Thread method start in line (H) to make the thread runnable. This is repeated in the rest of main for the other two threads.

[5]In fact, Thread also implements the Runnable interface. So every Thread is an object of type Runnable.




Programming With Objects[c] A Comparative Presentation of Object-Oriented Programming With C++ and Java
Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java
ISBN: 0471268526
EAN: 2147483647
Year: 2005
Pages: 273
Authors: Avinash Kak

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net