/************************************************************** ** ** Program : thread_ex.java ** ** Author : Ryan J. Stradling ** ** Created : July 31, 1996 ** ** Revisions : ** ** Purpose : This applet will display two buttons and two ** numbers. When you click on a button the corresponding ** number will increment. If you click on it again it ** will stop counting. This is to show the independence ** of threads. The numbers only count to 50 and then ** stop. ** ***************************************************************/ import java.awt.*; public class thread_ex extends java.applet.Applet implements Runnable { /* APPLET */ final static int NUMCOUNTERS = 2; final static int SPACING = 23; Counter[] counters = new Counter[NUMCOUNTERS]; Thread updateThread = null; boolean[] clicked = new boolean[NUMCOUNTERS]; public void init() { /* Make new counters */ for (int i = 0; i < NUMCOUNTERS; i++) { counters[i] = new Counter(); counters[i].setPriority(2); clicked[i] = false; } /* Make updateThread for drawing */ if (updateThread == null ) { updateThread = new Thread(this, "Count Program"); updateThread.setPriority(NUMCOUNTERS+2); } /* Make on/off buttons for threads */ for (int i = 0; i< NUMCOUNTERS; i++) { add(new Button(("ON/OFF " + i))); } } public boolean action (Event evt, Object arg) { /* check for button pushes */ if (evt.target instanceof Button) { check_button((String)arg); return true; } else return false; } void check_button(String bname) { // Start updateThread if (!updateThread.isAlive()) updateThread.start(); for (int i = 0; i 50 for (int i = 0; i < NUMCOUNTERS; i++) { if (counters[i].count <= 50) { repaint(); try { updateThread.sleep(1000); } catch (InterruptedException e) {} } else counters[i].stop(); } for (int i = 0; i < NUMCOUNTERS; i++) { if (counters[i] != null) if (counters[i].count > 50) stop(); } } } public void stop() { // Stops all threads for (int i = 0; i< NUMCOUNTERS; i++) { if (counters[i].isAlive()) { counters[i] = null; } } if (updateThread.isAlive()) { updateThread = null; } } }