实验十四:线程设计

1、制作数字化倒计时牌,计时单位可以用秒、分货天。例如奥运会倒计时100天

package TestCountDown;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.*;

public class CountDown extends JFrame {

JButton jButton;

JLabel jLabel;

int time=60;

public CountDown() {

FlowLayout fl=new FlowLayout(FlowLayout.CENTER);

this.setLayout(fl);

jButton=new JButton("重新开始");

jButton.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent arg0) {

dispose();

new CountDown();

}

);

jLabel=new JLabel();

new Thread(){

public void run() {

while(time>0) {

time--;

if(time<6) {

jLabel.setForeground(Color.RED);

}

jLabel.setText(time+"秒");

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}.start();

this.add(jButton);

this.add(jLabel);

this.setTitle("倒计时");

this.setSize(300, 200);

this.setResizable(true);

this.setVisible(true);

this.setDefaultCloseOperation(EXIT_ON_CLOSE);

}

public static void main(String[] args) {

new CountDown();

}

}

2.实验心得

        使用java.lang.Thread类或者java.lang.Runnable接口编写代码来定义、实例化和启动新线程。

Java中,每个线程都有一个调用栈,即使不在程序中创建任何新的线程,线程也在后台运行着。一

个Java应用总是从main()方法开始运行,mian()方法运行在一个线程内,它被称为主线程。扩展

java.lang.Thread类。此类中有个run()方法,应该注意其用法:public void run()如果该线程是使用

独立的Runnable运行对象构造的,则调用该Runnable对象的run方法;否则,该方法不执行任何操

作并返回。

posted on 2019-06-30 19:23  我是wyw  阅读(315)  评论(0编辑  收藏  举报