Docstoc

Graphics

Document Sample
Graphics Powered By Docstoc
					    159.235 Graphics & Graphical
            Programming
          Lecture 18 - Introduction to
                    Threads



159.235               Graphics           1
            Intro to Threads- Outline
• What is a Thread?
• Uses in Timing or Animation in Games and
  Simulation
• Many systems are in fact multi-threaded - you do not
  always see or need to be aware of the system threads
  working in the background
• Java has several systems threads for the Garbage
  Collector and for the AWT graphics system
• Using Java inbuilt thread facilities

  159.235                 Graphics                   2
                     What is A Thread?
• Normally we think of our • A multi-threaded program
  program as being a single has a set of “virtual CPUs”
  thread of control           • Each has its own thread of
• The CPU architecture          control, linked to a separate
  has:                          program counter
   – A program (compiled      • Threads generally share the
     code)                      program code and memory
   – A program counter          allocation of a single
   – Program context - ie       program (unlike eg full
     memory allocated, values
                                “processes”)
      in registers
   159.235                  Graphics                    3
            Cooperating threads
• Several threads running      • Think of threads as a
  the same program can           way of conceptualising
  usefully cooperate to          or managing a
  help the user achieve an       concurrent or parallel
  outcome                        program that can
• eg managing the                effectively “do” several
  windows system or              things at once
  mouse and keyboard

  159.235                Graphics                      4
                Using Threads
• Needs careful planning in • Threads libraries are
  the general case            available for common
• Need to consider what       programming languages
  each thread will do…        like C or C++
• How will they be          • Java has a threads
  initialised?                system integrated into
• How will they exchange      the language
  information (eg shared
  variables)                • Thread object or
                              Runnable interface
  159.235               Graphics                  5
                 Java Threads
• The Java Virtual             • AWT graphics thread
  Machine (JVM has               looks after the various
  several system threads         events that can occur
  that help your program         ina program such as
  run                            mouse of keyboard
                                 events
• Garbage Collector thread
  wakes up periodically        • You can program
  and recovers memory            threads by supplying
  no longer used by              methods to dictate what
  unreferenced objects           they will do under
                                 certain circumstances
  159.235                Graphics                    6
            Java Thread Methods
• As well as a start()         • Normally we just worry
  method that kicks a            about the run() method
  thread off                   • The system-supplied
• You can stop a thread          start method will call
  if your code has kept a        our run() method
  reference to it                anyway
                               • We just have to worry
                                 about some semantics
                                 of timing and interrupts
  159.235                   Graphics                        7
            Uses of Threads
• A separate thread is      • A character moves so
  useful in a graphical       many times per second
  program for timing        • Animation requires
  purposes                    refresh of the frame
• For example ina game        so many times per
  or simulation we            second
  might want some part      • A simulation might
  of our application to       require an update
  occur every so often        every so often
159.235               Graphics                    8
            Use conservatively
• Often we do not need         • Menu actions are
  a separate thread - just       dealt with by the
  use some existing one          system thread - we just
• Eg calls to the                supply some code for
  repaint() method in            it to call (action
  Java’s AWT graphics            Listeners)
  system just kick the
  AWT thread and tell          • Sometimes we do
  it to call our paint()         want a thread of our
  method                         own…
159.235                  Graphics                      9
   2 Ways of Creating Java Threads
• Create an object that         • Or, implement Runnable
  extends Thread                  interface in some class
• Override the methods we         of our own
  want to eg run()              • Provide a run method
• Create an instance of our     • new Thread(this);
  object from our normal
  code eg in main(), and
  invoke the thread’s
  start() method
  159.235                 Graphics                    10
import java.awt.*;     // Abstract Windowing Toolkit
import java.awt.event.*; // Event package - includes KeyListener
                                                                                       public void myUpdate(){
import javax.swing.*; // Swing graphics library                                             // changes to a random background colour
                                                                                            //col = Color.getHSBColor( (float)Math.random(), 0.9F, 1.0F );
// A program to demonstrate Timing from a separate Thread
public class MyProg15 extends JFrame implements KeyListener, Runnable{
                                                                                             // gradually cycle through the colours
  private Color col = Color.white; // use as background color for the frame
                                                                                             incrementColor();
  private Container con;    // keep a handle on the Frame's contentPane                      con.setBackground( col );
  private Thread loop = null; // keep a handle on the Timer thread                           con.repaint();
                                                                                         }
  public static void main( String args[] ){
      new MyProg15(); // run the JFrame
  }
                                                                                         // increment the present Hue:
                                                                                         public void incrementColor(){
  MyProg15(){                                                                                float hsb[] = Color.RGBtoHSB(col.getRed(),col.getGreen(),
     super("Playing with Threads");                                                          col.getBlue(), null);
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                                         float h = hsb[0];
     setResizable( false );                                                                  h += 0.005;
     con = getContentPane();
     con.setLayout( new BorderLayout() );
                                                                                             col = Color.getHSBColor( h, 1.0F, 1.0F );
     addKeyListener( this ); // make this object be the one to listen to keyboard        }

      JLabel text = new JLabel("Type q or Q to quit");
      text.setBackground( col );
      text.setFont( new Font( "Palatino", Font.ITALIC, 28) );
      con.add( text ); // add simple text label directly to the JFrame
                                                                                       • This is using the Hue, Saturation
      setSize( 256, 256 );
      setVisible( true );
                                                                                         Brightness (HSB) color model
      loop = new Thread(this); // create separate thread to run our Timer              • Useful to give random colours
  }
      loop.start();                                 // and start it
                                                                                         from a single random number
             159.235                                                                Graphics                                                    11
    // Three methods that satisfy the KeyListener interface:
     public void keyPressed( KeyEvent kev ){}
     public void keyReleased( KeyEvent kev ){}

     public void keyTyped( KeyEvent kev ){ // useful only for "normal" characters
                                                                                          • MyProg15 shows a
        if( kev.getKeyChar() == 'q' || kev.getKeyChar() == 'Q' ){ // q or Q for "quit"
           System.exit(1);
                                                                                            typical use of a timing
                                                                                            thread ina graphics
        }else if( kev.getKeyChar() == 'r' || kev.getKeyChar() == 'R' ){
           col = Color.red;
        }else if( kev.getKeyChar() == 'g' || kev.getKeyChar() == 'G' ){
           col = Color.green;
        }else if( kev.getKeyChar() == 'b' || kev.getKeyChar() == 'B' ){                     program
           col = Color.blue;

     }
        }
                                                                                          • It sleeps and wakes
     // the method prerscribed by the Runnable interface
     public void run(){
                                                                                            up very so often to do
          System.out.println("run called ");
          long delayTime = 1000/5; // millisecs / frames-per-sec                            something
          long startTime, waitTime, elapsedTime;
          Thread th = Thread.currentThread();
          while ( loop == th ){                                                           • eg move a character or
             startTime = System.currentTimeMillis();                                        in this case change the
             myUpdate(); // do something
                                                                                            background colour
             elapsedTime = System.currentTimeMillis() - startTime;
             waitTime = Math.max( delayTime - elapsedTime, 5 );
             try{
                      Thread.sleep(waitTime);
                                                                                          • Note delays are in
         }
             }catch( InterruptedException e ){}
                                                                                            milliseconds
     }
}

                 159.235                                                            Graphics                     12
          MyProg15 Output




159.235         Graphics    13
                   MyProg15
• This program                 • Remember a given
  implements the                 computer may not be
  Runnable interface and         able to keep up with
  supplies a run method          arbitrarily high frame
                                 per second rates
• The run method               • Typically 5-10 should
  contains a timer loop to       work on most modern
  do something at so             machines
  many frame updates per       • Depends on the
  second                         requested task
  159.235                Graphics                     14
            Changing the Colours
• In MyProg15 we just           • Uses Math.random() a
  ask our run method to           static method that
  call some method that           return a random
  changes the colour of the       number between 0.0
                                  and 1.0
  Frame
                                • The Hue, Saturation,
• Not a very demanding            Brightness colour
  task                            model lets us just
                                  tinker with the colour
                                  in one single number
  159.235                 Graphics                     15
              Summary - Threading
• Threading is powerful •    Understanding the full scope of
• but dangerous!             threads and concurrent
• Use with caution!          programming is a paper in itself
• Use in a well thought •    We have introduced a simple
  through design pattern     use of a Java thread for
  or template                graphical and animation
                             programs
• The system has several
  auxiliary threads that •   Remember timing constants
  may suffice for our        are usually highly non portable
  programs                   across different computers


    159.235                  Graphics                   16

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:0
posted:4/20/2013
language:Unknown
pages:16