//: c14:Stop.java modified fron Interrupt.java // From 'Thinking in Java, 2nd ed.' by Bruce Eckel // www.BruceEckel.com. See copyright notice in CopyRight.txt. // The alternative approach to using // stop() when a thread is stopped. // // import javax.swing.*; import java.awt.*; import java.awt.event.*; import com.bruceeckel.swing.*; public class Stop extends JApplet { JTextArea Xout = new JTextArea(5, 15); private JButton stopB = new JButton("Stop"); private Stopped stoppedT = new Stopped(); public void init() { Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(stopB); cp.add(new JScrollPane(Xout)); stoppedT.start(); stopB.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { stopB.setEnabled(false); stopB.setBackground(Color.red); stoppedT.requestStop(); stoppedT = null; // to release it } }); } class Stopped extends Thread { // Must be volatile: private volatile boolean stopF = false; private int counter = 0; public synchronized void run() { while(!stopF) { Xout.append("counter: " + counter++ + "\n"); try { sleep(2000); } catch(InterruptedException e) { System.err.println("Interrupted"); } } if(stopF) Xout.append("Detected stop"); } public void requestStop() { stopF = true; } } public static void main(String[] args) { Console.run(new Stop(), 200, 100); } } ///: