7-1 创建一个倒数计数线程

  • Post author:
  • Post category:其他


创建一个倒数计数线程。要求:1.该线程使用实现Runnable接口的写法;2.程序该线程每隔0.5秒打印输出一次倒数数值(数值为上一次数值减1)。

输入格式:

N(键盘输入一个整数)

输出格式:

每隔0.5秒打印输出一次剩余数

输入样例:

6

输出样例:

在这里给出相应的输出。例如:

6
5
4
3
2
1
0

参考代码如下:

import java.util.Scanner;

class MThread implements Runnable{
    public void run(){
        Scanner sc = new Scanner(System.in);
        int c = sc.nextInt();
        for(int i = c; i>=0; i--){
            System.out.println(i);
            try{//异常处理
                Thread.sleep(500);//休眠500毫秒
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
public class Main{
    public static void main(String[] args) throws Exception{
        Thread t = new Thread(new MThread());
        t.start();//倒计时功能交由线程类执行
    }
}