import java.awt.*;
import java.awt.event.*;
import java.util.concurrent.*;
import javax.swing.*;
public class RunAndStop {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new RunAndStopFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class RunAndStopFrame extends JFrame {
public RunAndStopFrame() {
setTitle("Run and Stop");
RunAndStopComponent component = new RunAndStopComponent();
add(component, BorderLayout.CENTER);
final RunAndStopThread runAndStop = new RunAndStopThread(component);
final JButton runButton = new JButton("运行");
runButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
if(runAndStop.getRun()) {
//处于暂停状态
runButton.setText("运行");
runAndStop.setStop();
} else {
//处于运行状态
if(first) {
//是第一次运行程序,才调用start方法,并且控制整个程序的flag置为true
first = false;
runAndStop.setFlag(true);
Thread t = new Thread(runAndStop);
t.start();
}
runButton.setText("暂停");
runAndStop.setRun();
}
}
});
JButton stepButton = new JButton("停止");
stepButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
//停止程序
runAndStop.setFlag(false);
runButton.setText("重新开始");
first = true;
runAndStop.setStop();
}
});
JPanel buttons = new JPanel();
buttons.add(runButton);
buttons.add(stepButton);
add(buttons, BorderLayout.SOUTH);
setSize(300, 300);
}
public static boolean first = true;
}
class RunAndStopThread implements Runnable {
public RunAndStopThread(RunAndStopComponent component) {
this.component = component;
this.gate = new Semaphore(1);
this.run = false;
this.flag = false;
}
public void setRun() {
run = true;
gate.release();
}
public void setStop() {
run = false;
gate.release();
}
public boolean getRun() {
return this.run;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
int i = 0;
try {
while(flag) {
if(run) {
component.setString("this is a test String." + i);
i++;
Thread.sleep(800);
} else {
gate.acquire();
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private RunAndStopComponent component;
private Semaphore gate;
private volatile boolean run;//控制开始和暂停
private volatile boolean flag;//控制整个程序停止
}