// import javax.swing.*; import java.awt.*; import java.awt.event.*; import com.bruceeckel.swing.*; public class Interrupt extends JApplet { private JTextField txt = new JTextField(30); private JButton suspendB = new JButton("Suspend"), interruptB = new JButton("Interrupt"); private Suspendable suspendableThread = new Suspendable(); class Suspendable extends Thread implements Runnable { private int count = 0; private boolean suspendedFlag = false; public Suspendable() { start(); } public synchronized void funSuspend() { suspendedFlag = true; } public synchronized void funInterrupt() { suspendedFlag = false; interrupt(); } public void run() { while (true) { txt.setText("Count: " + Integer.toString(count++)); synchronized (this) { if(suspendedFlag) { try{ txt.setText("Suspend Button is ON: wait()"); wait(); } catch(InterruptedException e) { txt.setText("Interrupt Button is ON: "+ e); System.err.println("wait Interrupted "+ e); } } }// synch try{ sleep(2000); } catch(InterruptedException e) { System.err.println("sleep(): Interrupted " + e); } }//true }//run }//thread public void init() { Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(txt); suspendB.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { suspendableThread.funSuspend(); suspendB.setEnabled(false); suspendB.setBackground(Color.red); interruptB.setEnabled(true); interruptB.setBackground(Color.green); } } ); cp.add(suspendB); suspendB.setEnabled(true); suspendB.setBackground(Color.green); interruptB.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { suspendableThread.funInterrupt(); suspendB.setEnabled(true); suspendB.setBackground(Color.green); interruptB.setEnabled(false); interruptB.setBackground(Color.red); } } ); cp.add(interruptB); interruptB.setEnabled(false); interruptB.setBackground(Color.red); } public static void main(String[] args) { Console.run(new Interrupt(), 400, 200); } }//JApplet