Thursday, February 10, 2011

What Are Threads ?

What Are Threads ?

Let us start by looking at a program that does not use multiple threads and that , as a consequence, makes it difficult for the user to perform several task with that program . after we dissect it we will then show you how easy it is to have this program run separate thereads. this program animates a bounching ball by continually moving the ball, finding out if it bounces against a wall, and then redrawing it ( see figure 1 - 1 )

As soon as you clik on the " start " button , the program launches a bll from the upper - left corner of the screen and the ball begins bouncing , The handler of the " start" button calls the method bounce ( ) of the ball class, which contains a loop running through 1, 000 move . After each move , we call the static sleep method of the Thread calss to pause the ball for 5 millisecond



***********************************************************************************
Class Ball
{ . . .
Public void bounce ()
{ draw ()
For ( int i = 1 ; i <= 1000; i++ )
{ move () ;
Try
{ Thread.sleep ( 5 );
}
Catch ( Interrupt edException e )
{
}
}
}
}
***********************************************************************************
        Figure 1 - 1 : Using a thread to animate a bouncing ball

The call to Thread.sleep does not create a new thread- sleep is a stastic method of the Thread class that put the current thread to sleep. 
The sleep methoud can throw an Interrupt edException. we will discuss this exeption and its proper handling later; we just ignore if for now.
If you run the program , you can see that the ball bounces arround nicely , but it completely takes over the aplication . IF you become tired of the bouncing ball before ir has finished its 1,000 bounces and clik on the "close" button , the ball continues bouncing anyway . You cannot interact with the program until the ball has finished bouncing .

This is not a good sitution in theory or in practice, and it is bouncing more and more of a problem as network become more central . after all , when you are reading data over a network connection , it is all to common to be stuck in a time - consuming task that you would really like to interrupt. For example , suppose you download large image and decide , after seeing a piece of it , that you do need or want to see the rest; you certainly would like to be able to clik on a " stop" or "back" button to interupst the loding process. In the next section , we will show you how ti keep the user in control by running crucial parts of the code in a separate Thread
Example 1 - 1 is the entired code for the program 
***********************************************************************************
Example 1 - 1: Bounce.java

import java.awt. *;
import java.awt.event. *;
import javax.swing. *;

public class Bounce
{ public static void main ( String [] args )
   { Jframe frame = new BounceFrame ( ) ;
      Jframe.show;
}
 }

class BounceFrame extends JFrame
{ public BounceFrame ( )
  { set size ( 300 , 200 ) ;
     set Title ( " Bounce " ) ;
addWindowListener ( new windowAdapter ( )
{ public void windowClossing ( windowEvent e )
   { system.exit ( 0 );
    }
} ) ;

Container contentPane = getContentPane ( ) ;
canvas = new JPanel ( ) ;
contentPane.add ( canvas, " Center" );
JPanel p = new JPanel ( );
addButton ( p, "start",
    new ActionListener ( )
  { public void actionPerformed ( ActionEvent evt )
     { Ball b = new Ball ( canvas );
        b.bounce ( ) ;
}
}} ) ;

addButton ( p, "Close",new ActionListener  ( )
{ public void actionPerformed ( ActionEvent evt )
{ system.exit ( 0 ) ;
});
contentPane.add (p, "South" );
}
public void addButton  ( countainer c, String title, ActionListener a )
{ JButton b = new Jbutton ( title ) ;
   c.add ( b ) ;
   b.addActionListener ( a );
}
private Jpanel canvas ;
}

class Ball
{ public Ball ( JPanel b ) { box = b; }

  public void draw ( )
{Grapihics g = boxgetGraphics ( );
  g.filloval ( x,y, XSIZE, YSIZE );
  g.dispose ( );
}

public void move ( )
{ Graphics g = box getGraphics ( ) ;
   g.setXORMODE ( box.getBackground () );
   g.filloval ( x, y, XSIZE, YSIZE);
   x + = dx ;
   y + = dy ;
dimension d = box.getSize ( )
if ( x < 0 )
   { x = 0; dx = -dx ; }
    if ( x + XSIZE >= d.width )
     { x = d.width - XSIZE; dx = -dx; }
if ( y < 0 )
{ y = 0; dy = -dy; }
if ( y + YSIZE >= d.height )
 { y = d.height - YSIZE; dy = -dy; }
  g.fillovall ( x,y, XSIZE, YSIZE );
  g.dispose ( );
}
{ draw ( );
   for ( int i = 1; i <= 1000; i++)
{ move ( );
 try { Thread.sleep ( 5 ) ; }
catch ( InterruptedException e ) { }
 }
}
private JPanel box ;
private static final int XSIZE = 10 ;
private ststic final int YSIZE =  10;
private int x = 0 ;
private int y = 0 ;
private int dx = 2 ;
private int dy = 2 ;
}
***********************************************************************************
note : in the example program , we use the XOR drawing mode o simulation the move ment of the ball. This makes the program very simple so that you can focus on the thread details as we build up this example , however , the display quality is compromised wit this approach since ovelapping balls are not displayed correctly. A better approach would be following keep a vector of all balls in BouncePanel . its paintComponent methodshould ask all balls to draw themselves. force a repaint of the panel in the move method however , we leave this improvement asa the provebial exercise for the reader .

1 comment: