在java程序中利用线程

java

package 第十一章;

import java.awt.Button;

import java.awt.Color;

import java.awt.Font;

import java.awt.Frame;

import java.awt.Label;

import java.awt.Panel;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.*;

public class shijian extends Frame {

Panel pan=new Panel();

Label lbl=new Label();

Button btn1=new Button("开始");

Button btn2=new Button("停止");

boolean p=true;

public shijian(String str) {

super(str);

}

public shijian(){

buju();

}

public static void main(String agrs[]){

shijian sj=new shijian();

}

public void buju(){

shijian f=new shijian("显示时间");

f.setSize(500,500);

f.setBackground(Color.gray);

f.setLayout(null);

f.setVisible(true);

pan.setSize(500, 500);

pan.setLocation(0, 0);

pan.setBackground(Color.darkGray);

pan.setLayout(null);

lbl.setSize(300,100);

lbl.setLocation(100, 100);

lbl.setBackground(Color.yellow);

// lbl.setFont();

Font kl=new Font("宋体",0,25);

lbl.setFont(kl);

btn1.setSize(100,50);

btn1.setLocation(100, 250);

btn2.setSize(100,50);

btn2.setLocation(300, 250);

pan.add(btn2);

pan.add(btn1);

pan.add(lbl);

f.add(pan);

// 监听开始事件

btn1.addActionListener(new ActionListener(){

@Override

public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub

kaishi(e);

}});

// 监听停止事件

btn2.addActionListener(new ActionListener(){

@Override

public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub

tingzhi(e);

}});

}

// 点击开始时调用

public void kaishi(ActionEvent e){

p=true;

Thread t=new Thread(){

public void run() {

// TODO Auto-generated method stub

while(p){

Date d=new Date();

lbl.setText(d.toLocaleString());

try {

Thread.sleep(1000);

} catch (InterruptedException e1) {

e1.printStackTrace();

}

}

}

};

t.start();

}

public void tingzhi(ActionEvent e){

// Thread t=new Thread(){

// public void run() {

// TODO Auto-generated method stub

p=false;

// }

// };

}

}

以上是 在java程序中利用线程 的全部内容, 来源链接: utcz.com/z/393163.html

回到顶部