Example9_12
来源:互联网 发布:儿童读物在线阅读软件 编辑:程序博客网 时间:2024/06/05 06:24
package itat;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Date;
public class Example9_12 {
public static void main(String[] args){
new Win1();
}
}
class Win1 extends Frame implements Runnable,ActionListener{
Thread thread=null;
TextArea text=null;
Button buttonStart=new Button("Start");
Button buttonStop=new Button("Stop");
boolean die;
Win1(){
thread=new Thread(this);
text=new TextArea();
add(text,BorderLayout.CENTER);
Panel p=new Panel();
p.add(buttonStart);
p.add(buttonStop);
buttonStart.addActionListener(this);
buttonStop.addActionListener(this);
add(p,BorderLayout.NORTH);
setVisible(true);
setSize(500,500);
validate();
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void run() {
// TODO Auto-generated method stub
while(true){
text.append("/n"+new Date());
try {
thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(die==true){
return;
}
}
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==buttonStart){
if(!(thread.isAlive())){
thread=new Thread(this);
die=false;
}
try{
thread.start();
}catch(Exception eh){
text.setText("线程没有结束run()方法之前,不要再调用start()方法");
}
}
else if(e.getSource()==buttonStop){
die=true;
}
}
}