62,620
社区成员
发帖
与我相关
我的任务
分享
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/*
* 线程类,运行时在文本区显示变化的数据。
*/
class ThreadClass1 implements Runnable {
private JTextField textField; // 用于显示变化的数据文本区。
private int loop = 0; // 辩护的数据计数。
private boolean continueRun = true; // 控制线程的结束。
// set get 方法
public boolean isContinueRun() {
return continueRun;
}
public void setContinueRun(boolean continueRun) {
this.continueRun = continueRun;
}
// 构造函数
public ThreadClass1(JTextField textField) {
this.textField = textField;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (continueRun) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
textField.setText("The " + loop++ + "times out");// 每休眠10ms输出一次。
}
}
}
/*
* 主类
*/
public class TestAlive1 extends JFrame {
private static final long serialVersionUID = 1L;
private Thread t1 = null; // 定义一个线程变量。
private ThreadClass1 tc = null;
// 定义2个按钮
private JButton buttonStart;
private JButton buttonStop;
// 定义面板
private JPanel jPanel;
private JTextField textField;
private JTextField textField1; // 显示状态
public TestAlive1() {
textField = new JTextField("result");
textField1 = new JTextField("state");
tc = new ThreadClass1(textField);
buttonStart = new JButton("start");
buttonStart.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (null == t1) {// 线程第一次启动
t1 = new Thread(tc);
tc.setContinueRun(true);
t1.start();
textField1.setText("t1 start the first time!");
return;
} else if (t1.isAlive()) {// 线程在启动中,按"start"键
textField1.setText("t1 is started and is alive!!!");
return;
}// 线程结束后按"start"启动新的线程
t1 = new Thread(tc);
tc.setContinueRun(true);
t1.start();
textField1
.setText(" A new thread t1 is started and is alive!!!");
}
});
buttonStop = new JButton("stop");
buttonStop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (t1.isAlive()) {// 线程活动时按"stop"键结束线程
tc.setContinueRun(false);
textField1.setText("The thread t1 is stoped!!");
} else {// 线程已经结束在按"stop"键。
textField1
.setText("the thread t1 is died please start a new thread!!");
// System.out.println("the thread t1 is died");
}
}
});
jPanel = new JPanel(new FlowLayout());
Container c = getContentPane();
c.setLayout(new BorderLayout());
jPanel.add(buttonStart);
jPanel.add(buttonStop);
c.add(jPanel, BorderLayout.NORTH);
c.add(textField1, BorderLayout.CENTER);
c.add(textField, BorderLayout.SOUTH);
setSize(300, 200);
setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//入口
public static void main(String[] args) {
new TestAlive1();
}
}