Java Programing

June 15, 2007

2.4.3 The Runnable Interface We’ve used the second

Filed under: Java Programming — webmaster @ 1:12 am

2.4.3 The Runnable Interface We’ve used the second technique in the HelloJava4 example. To create a thread, a HelloJava4 object passes itself (this) to the Thread constructor. This means that HelloJava4 itself must implement the Runnable interface, by implementing the run( ) method. This method is called automatically when the runtime system needs to start the thread. We indicate that the class implements the interface in our class declaration: public class HelloJava4 extends JComponent implements MouseMotionListener, ActionListener, Runnable {…} At compile time, the Java compiler checks to make sure we abide by this statement. We have carried through by adding an appropriate run( ) method to HelloJava4. It takes no arguments and returns no value. Our run( ) method accomplishes blinking by changing the color of our text a couple of times a second. It’s a very short routine, but we’re going to delay looking at it until we tie up some loose ends in dealing with the Thread itself. 2.4.4 Starting the Thread We want the blinking to begin when the application starts. So we’ll start the thread in the initialization code in HelloJava4’s constructor. It takes only two lines: Thread t = new Thread(this); t.start( ); First, the constructor creates a new instance of Thread , passing it the object that contains the run( ) method to the constructor. Since HelloJava4 itself contains our run( ) method, we pass the special variable this to the constructor. this always refers to our object. After creating the new Thread, we call its start( ) method to begin execution. This, in turn, invokes HelloJava4’s run( ) method in a separate thread. 2.4.5 Running Code in the Thread Our run( ) method does its job by setting the value of the variable blinkState. We have added blinkState, a boolean value, to represent whether we are currently blinking on or off: boolean blinkState; A setColor( ) call has been added to our paintComponent( ) method to handle blinking. When blinkState is true, the call to setColor( ) draws the text in the background color, making it disappear: g.setColor(blinkState ? getBackground() : currentColor( )); Here we are being somewhat terse, using the C-like ternary operator to return one of two alternative color values based on the value of blinkState. Finally, we come to the run( ) method itself: public void run( ) { try { - 51

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URI

Sorry, the comment form is closed at this time.

Powered by Java Web Hosting