1 / 16

159.235 Graphics & Graphical Programming

159.235 Graphics & Graphical Programming. Lecture 18 - Introduction to Threads. 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

angelo
Download Presentation

159.235 Graphics & Graphical Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 159.235 Graphics & Graphical Programming Lecture 18 - Introduction to Threads Graphics

  2. 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 Intro to Threads- Outline Graphics

  3. Normally we think of our program as being a single thread of control The CPU architecture has: A program (compiled code) A program counter Program context - ie memory allocated, values in registers A multi-threaded program has a set of “virtual CPUs” Each has its own thread of control, linked to a separate program counter Threads generally share the program code and memory allocation of a single program (unlike eg full “processes”) What is A Thread? Graphics

  4. Several threads running the same program can usefully cooperate to help the user achieve an outcome eg managing the windows system or mouse and keyboard Think of threads as a way of conceptualising or managing a concurrent or parallel program that can effectively “do” several things at once Cooperating threads Graphics

  5. Needs careful planning in the general case Need to consider what each thread will do… How will they be initialised? How will they exchange information (eg shared variables) Threads libraries are available for common programming languages like C or C++ Java has a threads system integrated into the language Thread object or Runnable interface Using Threads Graphics

  6. The Java Virtual Machine (JVM has several system threads that help your program run Garbage Collector thread wakes up periodically and recovers memory no longer used by unreferenced objects AWT graphics thread looks after the various events that can occur ina program such as mouse of keyboard events You can program threads by supplying methods to dictate what they will do under certain circumstances Java Threads Graphics

  7. As well as a start() method that kicks a thread off You can stop a thread if your code has kept a reference to it Normally we just worry about the run() method The system-supplied start method will call our run() method anyway We just have to worry about some semantics of timing and interrupts Java Thread Methods Graphics

  8. A separate thread is useful in a graphical program for timing purposes For example ina game or simulation we might want some part of our application to occur every so often A character moves so many times per second Animation requires refresh of the frame so many times per second A simulation might require an update every so often Uses of Threads Graphics

  9. Often we do not need a separate thread - just use some existing one Eg calls to the repaint() method in Java’s AWT graphics system just kick the AWT thread and tell it to call our paint() method Menu actions are dealt with by the system thread - we just supply some code for it to call (action Listeners) Sometimes we do want a thread of our own… Use conservatively Graphics

  10. Create an object that extends Thread Override the methods we want to eg run() Create an instance of our object from our normal code eg in main(), and invoke the thread’s start() method Or, implement Runnable interface in some class of our own Provide a run method new Thread(this); 2 Ways of Creating Java Threads Graphics

  11. import java.awt.*; // Abstract Windowing Toolkit import java.awt.event.*; // Event package - includes KeyListener import javax.swing.*; // Swing graphics library // A program to demonstrate Timing from a separate Thread public class MyProg15 extends JFrame implements KeyListener, Runnable{ private Color col = Color.white; // use as background color for the frame private Container con; // keep a handle on the Frame's contentPane private Thread loop = null; // keep a handle on the Timer thread public static void main( String args[] ){ new MyProg15(); // run the JFrame } MyProg15(){ super("Playing with Threads"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable( false ); con = getContentPane(); con.setLayout( new BorderLayout() ); 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 setSize( 256, 256 ); setVisible( true ); loop = new Thread(this); // create separate thread to run our Timer loop.start(); // and start it } public void myUpdate(){ // changes to a random background colour //col = Color.getHSBColor( (float)Math.random(), 0.9F, 1.0F ); // gradually cycle through the colours incrementColor(); con.setBackground( col ); con.repaint(); } // increment the present Hue: public void incrementColor(){ float hsb[] = Color.RGBtoHSB(col.getRed(),col.getGreen(), col.getBlue(), null); float h = hsb[0]; h += 0.005; col = Color.getHSBColor( h, 1.0F, 1.0F ); } This is using the Hue, Saturation Brightness (HSB) color model Useful to give random colours from a single random number Graphics

  12. // 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 if( kev.getKeyChar() == 'q' || kev.getKeyChar() == 'Q' ){ // q or Q for "quit" System.exit(1); }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' ){ col = Color.blue; } } // the method prerscribed by the Runnable interface public void run(){ System.out.println("run called "); long delayTime = 1000/5; // millisecs / frames-per-sec long startTime, waitTime, elapsedTime; Thread th = Thread.currentThread(); while ( loop == th ){ startTime = System.currentTimeMillis(); myUpdate(); // do something elapsedTime = System.currentTimeMillis() - startTime; waitTime = Math.max( delayTime - elapsedTime, 5 ); try{ Thread.sleep(waitTime); }catch( InterruptedException e ){} } } } MyProg15 shows a typical use of a timing thread ina graphics program It sleeps and wakes up very so often to do something eg move a character or in this case change the background colour Note delays are in milliseconds Graphics

  13. MyProg15 Output Graphics

  14. This program implements the Runnable interface and supplies a run method The run method contains a timer loop to do something at so many frame updates per second Remember a given computer may not be able to keep up with arbitrarily high frame per second rates Typically 5-10 should work on most modern machines Depends on the requested task MyProg15 Graphics

  15. In MyProg15 we just ask our run method to call some method that changes the colour of the Frame Not a very demanding task Uses Math.random() a static method that return a random number between 0.0 and 1.0 The Hue, Saturation, Brightness colour model lets us just tinker with the colour in one single number Changing the Colours Graphics

  16. Threading is powerful but dangerous! Use with caution! Use in a well thought through design pattern or template The system has several auxiliary threads that may suffice for our programs Understanding the full scope of threads and concurrent programming is a paper in itself We have introduced a simple use of a Java thread for graphical and animation programs Remember timing constants are usually highly non portable across different computers Summary - Threading Graphics

More Related