Web server logs - Chapter 15 Multithreading 871 The applet class RandomCharactersdisplays
Chapter 15 Multithreading 871 The applet class RandomCharactersdisplays three JLabels and three JCheck- Boxes. A separate thread of execution is associated with each JLabel and button pair. Each thread randomly displays letters from the alphabet in its corresponding JLabel object. The applet defines the Stringalphabet(line 16) containing the letters from A to Z. This string is shared among the three threads. The applet s startmethod (lines 52 65) instantiates three Thread objects (lines 59 60) and initializes each with an instance of class RunnableObject, which implements interface Runnable. Line 63 invokes the Threadclass startmethod on each Thread, placing the threads in the ready state. Class RunnableObject is defined at lines 115 185. Its run method (line 120) defines two local variables. Line 123 uses static method currentThread of class Threadto determine the currently executing Threadobject. Line 125 calls the applet s utility method getIndex(defined at lines 68 76) to determine the index of the currently executing thread in the array threads. The current thread displays a random character in the JLabel object with the same indexin array outputs. 1 // Fig. 15.17: RandomCharacters.java 2 // Demonstrating the Runnable interface. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class RandomCharacters extends JApplet 12 implements ActionListener { 13 14 // declare variables used by applet and 15 // inner class RunnableObject 16 private String alphabet = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”; 17 private final static int SIZE = 3; 18 19 private JLabel outputs[]; 20 private JCheckBox checkboxes[]; 21 22 private Thread threads[]; 23 private boolean suspended[]; 24 25 // set up GUI and arrays 26 public void init() 27 { 28 outputs = new JLabel[ SIZE ]; 29 checkboxes = new JCheckBox[ SIZE ]; 30 threads = new Thread[ SIZE ]; 31 suspended = new boolean[ SIZE ]; 32 33 Container container = getContentPane(); 34 container.setLayout( new GridLayout( SIZE, 2, 5, 5 ) ); Fig. 15.17 Demonstrating the Runnableinterface, suspending threads and resuming threads (part 1 of 5).
Check Tomcat Web Hosting services for best quality webspace to host your web application.