The
start and
interrupt methods are in the Thread class api. (One of) The Thread constructor(s) takes a Runnable as an argument. The Runnable interface has a single method:
run. We don't call run directly but start up a Thread which does the work of calling the run method which runs until completion/the method returns or ends.
Here is an example of how you can put these together to make a timer.
import java.awt.event.*;
import javax.swing.*;
public class ConcurrencyExample implements Runnable,
ActionListener {
JLabel label;
Thread thread;
boolean running;
long delay = 1000;
int count = 0;
public void run() {
while(running) {
try {
Thread.sleep(delay);
} catch(InterruptedException e) {
System.out.println("interrupted");
stop();
}
label.setText("count = " + count++);
}
}
private void start() {
if(!running) {
running = true;
thread = new Thread(this);
thread.setPriority(Thread.NORM_PRIORITY);
thread.start();
}
}
public void stop() {
running = false;
if(thread != null)
thread.interrupt(); // wake up
thread = null;
}
public void actionPerformed(ActionEvent e) {
String ac = e.getActionCommand();
if(ac.equals("START"))
start();
if(ac.equals("STOP"))
stop();
}
private JLabel getCenter() {
label = new JLabel("", JLabel.CENTER);
return label;
}
private JPanel getControls() {
String[] ids = { "start", "stop" };
JPanel panel = new JPanel();
for(int j = 0; j < ids.length; j++) {
JButton button = new JButton(ids[j]);
button.setActionCommand(ids[j].toUpperCase());
button.addActionListener(this);
panel.add(button);
}
return panel;
}
public static void main(String[] args) {
ConcurrencyExample test = new ConcurrencyExample();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(test.getCenter());
f.getContentPane().add(test.getControls(), "Last");
f.setSize(300,160);
f.setLocation(200,200);
f.setVisible(true);
}
}
For background and discussion see the basic lesson on threads in java
Lesson: Concurrency and the more specialized
Lesson: Concurrency in Swing which deals with the event dispatch thread/single thread issues in swing.