用事件控制线程

在下面的程序中 单机start按钮线程开始工作,每隔1秒显示一次当前时间;单击stop按钮后,线程就结束了生命,释放了实体,即释放线程对象的内存

。每当单击start按钮,程序都让线程调用isAlive()方法,判断线程是否还有实体,如果线程是死亡状态就再分配实体给线程。

package Example12_11;
import java.awt.event.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.*;
public class Example12_11 {
	public static void main(String args[]){
		new Win();
	}
}
class Win extends JFrame implements Runnable,ActionListener{
	Thread showTime=null;
	JTextArea text=null;
	JLabel time;
	JButton buttonStart=new JButton("Start"),buttonStop=new JButton("Stop");
	boolean die;
	SimpleDateFormat m=new SimpleDateFormat("hh:mm:ss");
	Date date;
	Win(){
		showTime=new Thread(this);
		text=new JTextArea();
		add(new JScrollPane(text),BorderLayout.CENTER);
		JPanel p=new JPanel();
		time=new JLabel("现在时间:");
		time.setForeground(Color.BLUE);
		p.add(buttonStart);p.add(buttonStop);p.add(time);
		buttonStart.addActionListener(this);
		buttonStop.addActionListener(this);
		add(p,BorderLayout.NORTH);
		setVisible(true);
		setBounds(100,100,500,500);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	public void actionPerformed(ActionEvent e){
		if(e.getSource()==buttonStart){
			if(!(showTime.isAlive())){
				showTime=new Thread(this);
				die=false;
			}
			try{
				showTime.start();
			}
			catch(Exception e1){
				JOptionPane.showMessageDialog(this, "线程没有结束run方法之前,不要在调用start方法");
			}
		}
		else if(e.getSource()==buttonStop){
			die=true;
		}
	}
	public void run(){
		while(true){
			date=new Date();
			text.append("\n"+m.format(date));
			time.setText("现在时间"+m.format(date));
			try{
				Thread.sleep(1000);
			}
			catch(InterruptedException ee){}
			if(die==true)
				return ;
		}
	}
}


用事件控制线程_第1张图片

你可能感兴趣的:(事件控制线程)