Concurrent Programming with Java
Lab Manual, Version 1.0, F. Astha Ekadiyanto,
2002.
The function of ViewCanvas Class is to provide a graphical representation of the Threads that are controlled in the Applet. Each thread will occupy a bar of 500 pixels and the repaint() will be scheduled by a Timer Class. The different states are described as follows:
Create the ViewCanvas Class and replace with the codes below:
import java.awt.*; /** * The class ViewCanvas visualizes the threads in the monitor demonstration. * @author Stephan Fischli * @version 1.0 */ public class ViewCanvas extends Canvas { /** * The threads to visualize. */ private DemoThread[] threads; /** * The width of the canvas. */ private int width; /** * The height of the canvas. */ private int height; /** * The offscreen image used for double buffering. */ private Image image; /** * The graphics context of the offscreen image. */ private Graphics graphics; /** * The current time in seconds. */ private int time; /** * Creates a ViewCanvas object. * @param threads the threads to visualize */ public ViewCanvas( DemoThread[] threads ) { this.threads = threads; width = 540; height = 50*threads.length + 40; setSize( width, height ); } /** * Updates the canvas. * @param g the graphics context to use */ public void update( Graphics g ) { // create image if ( image == null ) { image = createImage( width, height ); graphics = image.getGraphics(); } // clear image if ( time == 0 ) { graphics.setColor( Color.white ); graphics.fillRect( 0, 0, width, height ); graphics.setColor( Color.black ); for ( int i = 0; i < threads.length; i++ ) graphics.drawLine( 20, 71 + 50*i, 520, 71 + 50*i ); } // draw activity of threads for ( int i = 0; i < threads.length; i++ ) { boolean running = false; Color color = Color.white; switch ( threads[i].getState() ) { case DemoThread.RUNNING: running = true; color = Color.green; break; case DemoThread.ENTERING_MONITOR: running = false; color = Color.green; break; case DemoThread.RUNNING_MONITOR: running = true; color = Color.red; break; case DemoThread.WAITING_CONDITION: running = false; color = Color.red; break; } graphics.setColor( color ); graphics.drawLine( 20 + time, 70 + 50*i, 20 + time, 70 + 50*i - (running?40:0) ); } // draw image g.drawImage( image, 0, 0, this ); time = (time + 1) % 500; } /** * Paints the canvas. * @param g the graphics context to use */ public void paint( Graphics g ) { if ( image != null ) g.drawImage( image, 0, 0, this ); } } |