选号程序
代码如下:
package a;
import java.awt.*;
import java.awt.event.*;
//六个标签线程,产生随机数
class MyLabel extends Label implements Runnable{
int value;
boolean stop=false;
public MyLabel(){
super("number");
value=0;
}
public void run(){
//自动生成方法存根
for(;;){
value=(int)(Math.random()*10);//产生一个0~9的数字
setText(Integer.toString(value));
try{
Thread.sleep(500);
}
catch(InterruptedException e){}
if(stop)//停止标记为true,退出循环,结束运行
break;
}
}
}
//主控线程,利用数组管理六个标签,利用判定条件结束子线程
public class cc extends Frame{
//六个随机选号线程,一个主控线程
MyLabel x[]=new MyLabel[6];//安排6个标签,每个标签显示1个数字
Button control;
public cc(String title){
super(title);
Panel disp=new Panel();
disp.setLayout(new FlowLayout());
for(int i=0;i<6;i++){
x[i]=new MyLabel();
disp.add(x[i]);
new Thread(x[i]).start();
}
add("Center",disp);
Button control=new Button("停止");
add("South",control);
pack();
setVisible(true);
control.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//自动生成方法存根
for(int i=0;i<6;i++)
x[i].stop=true;
}
}
);
}
public static void main(String args[]){
new cc("选号程序");
}
}
运行结果如下(左上角):
欢迎您关注我的微信公众号:学习微站(studysth)