//: c14:InterruptSleep.java
// From 'Thinking in Java, 2nd ed.' by Bruce Eckel
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
// The alternative approach to using suspend()
// and resume(), which are deprecated in Java 2.
// <applet code=InterruptSleep width=400 height=200>
// </applet>
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import com.bruceeckel.swing.*;
public class InterruptSleep extends JApplet {
private JTextField txt = new JTextField(30);
private JButton
interruptB = new JButton("Interrupt Sleep");
private Counting countingThread = new Counting();
class Counting extends Thread {
private int count = 0;
public Counting() {
start();
}
public synchronized void funInterrupt() {
System.err.println("Interrupt Button");
interrupt();
}
public void run() {
while (true) {
txt.setText("Count: " + Integer.toString(count++));
try{
sleep(8000);
}
catch(InterruptedException e) {
System.err.println("sleep(8 seconds): Interrupted");
}
}//true
}//run
}//thread
public void init() {
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(txt);
interruptB.addActionListener( new ActionListener() {
public
void actionPerformed(ActionEvent e) {
countingThread.funInterrupt();
}
}
);
cp.add(interruptB);
interruptB.setEnabled(true);
interruptB.setBackground(Color.green);
}
public static void main(String[] args) {
Console.run(new InterruptSleep(), 400, 200);
}
}//JApplet