您的位置:首页 > 编程语言 > Java开发

java线程控制,当stop按钮就停止,当start按钮就开始运行,当按stop时程序又停止的实现方法

2014-08-12 13:39 926 查看
package Test;

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;

public class a extends JFrame {
SheThread thread = null;

public a() {
try {
createFrame();
}
catch(Exception e) {
e.printStackTrace();
}
}

private void createFrame() {
JPanel jp = new JPanel(new FlowLayout());
this.add(jp);

JButton jbStart = new JButton("start ");
JButton jbEnd = new JButton("stop");
jp.add(jbStart);
jp.add(jbEnd);

this.setSize(300, 100);
this.setVisible(true);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

jbStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (thread != null)
thread.stop();
thread = new SheThread();
thread.start();
}
});
jbEnd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (thread != null)
thread.stop();
thread = null;
}
});
}

public static void main(String[] args) {
new a().show();
}

}

class SheThread extends Thread {
public SheThread() {
}

public void run() {
while (true) {
try {
sleep(1000);
} catch (InterruptedException e) {
}
System.out.println("this is a test!");
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐