//: c14:Suspend.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=Suspend width=300 height=100>
// </applet>
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import com.bruceeckel.swing.*;
public class Suspend extends JApplet {
private JTextField txt = new JTextField(10);
private JButton
suspendB = new JButton("Suspend"),
resumeB = new JButton("Resume");
private int SuspendCount = 1;
private Suspendable ssT = new Suspendable();
class Suspendable extends Thread {
private int count = 0;
private boolean suspendedF = false;
public Suspendable() { start(); }
public void funSuspend() {
suspendedF = true;
}
public synchronized void funResume() {
suspendedF = false;
notify();
}
public void run() {
while (true) {
try {
sleep(500);
synchronized(this) {
while(suspendedF) {
txt.setText("Suspend #: " + SuspendCount++);
wait();
}
}
} catch(InterruptedException e) {
System.err.println("Interrupted");
}
txt.setText(Integer.toString(count++));
}
}
}
public void init() {
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(txt);
suspendB.addActionListener(
new ActionListener() {
public
void actionPerformed(ActionEvent e) {
ssT.funSuspend();
suspendB.setEnabled(false);
suspendB.setBackground(Color.red);
resumeB.setEnabled(true);
resumeB.setBackground(Color.green);
}
});
cp.add(suspendB);
suspendB.setEnabled(true);
suspendB.setBackground(Color.green);
resumeB.addActionListener(
new ActionListener() {
public
void actionPerformed(ActionEvent e) {
ssT.funResume();
suspendB.setEnabled(true);
suspendB.setBackground(Color.green);
resumeB.setEnabled(false);
resumeB.setBackground(Color.red);
}
});
cp.add(resumeB);
resumeB.setEnabled(false);
resumeB.setBackground(Color.red);
}
public static void main(String[] args) {
Console.run(new Suspend(), 300, 100);
}
} ///:
} ///:~