Friday, February 11, 2011

Using Threads to Give Other Task a Chance

In our next program , we use two threads ; one for the bouncing ball and another for the main thread that take care of the user interface. Because each thread gets a chance to run , the main thread has the opportunity to notice when you click on the " close " button while the ball is bouncing . It can then process the " close " action. 

There is a simple procedure for running code in a separate thread: place the code into the run method of a class derived from Thread.
To make our bouncing - ball program into a separate thread , we need only derive ball from Thread and rename the bounce method run , as in the following code :

 

*************************************************************************************
class Ball extends Thread 
{ . . . 
  public void run ( )
  { try 
    { draw ( ) ;
         for ( int i = 1 ; i <= 1000;  i++ )
         { move ( );
            sleep ( 5 ) ;
}
}
catch ( InterruptedException e ) {}
}
}
***********************************************************************************

You may have noticed that we are catching an exception called InterruptedException. Method like sleep and wait throw this exception when your thread is interrupted because another thread has called the interrupt method. Interrupting a thread is a very dratic way of getting the thread' s attention , even when it is not active. typically, a thread is interrupted to terminate it . Accordingly , our run method exits when an interrupteException occurs.

No comments:

Post a Comment