Wednesday 2 March 2016

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 variable that can have the value true or false, 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 very terse, using the C language-style ternary operator to return one of two alternative color values based on the value of blinkState. If blinkState is true, the value is the value returned by the getBackground() method. If it is false, the value is the value returned by currentColor(). Finally, we come to the run() method itself:
 public void run() {  
 try {  
 while( true ) {  
 blinkState = !blinkState;  
 repaint();  
 Thread.sleep(300);  
 }  
 } catch (InterruptedException ie) {}  
 }  
Basically, run() is an infinite while loop, which means the loop runs continuously until the thread is terminated by the application exiting (not a good idea in general, but it works for this simple example). The body of the loop does three things on each pass:Flips the value of blinkState to its opposite value using the not operator (!), Calls repaint() to redraw the text and Sleeps for 300 milliseconds (about a third of a second). sleep() is a static method of the Thread class. The method can be invoked from anywhere and has the effect of putting the currently running thread to sleep for the specified number of milliseconds. The effect here is to give us approximately three blinks per second. The try/catch construct, described in the next section, traps any errors in the call to the sleep() method of the Thread class and, in this case, ignores them.

0 comments:

Post a Comment