7-1 创建一个倒数计数线程
创建一个倒数计数线程。要求:1.该线程使用实现Runnable接口的写法;2.程序该线程每隔0.5秒打印输出一次倒数数值(数值为上一次数值减1)。
输入格式:
N(键盘输入一个整数)
输出格式:
每隔0.5秒打印输出一次剩余数
输入样例:
6
输出样例:
在这里给出相应的输出。例如:
6
5
4
3
2
1
0
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Test t=new Test();
Thread th=new Thread(t);
th.start();
}
}
class Test implements Runnable {
public void run() {
Scanner in=new Scanner(System.in);
int n=in.nextInt();
for(int i=n;i>=0;i--)
{
System.out.println(i);
try{
Thread.sleep(500);
} catch (InterruptedException e) {//InterruptedException异常为恢复中断抛InterruptedException的代表方法有:
//1. java.lang.Object 类的 wait 方法
//2. java.lang.Thread 类的 sleep 方法
//3. java.lang.Thread 类的 join 方法
e.printStackTrace();//在命令行打印异常信息在程序中出错的位置及原因
}
}
}
}
7-2 程序改错题4
程序改错题。请修改下列代码,使程序能够输出正确的结果。
import java.util.Scanner; public class Main { public static void main(String[] args) { Thread t = new Thread(new RunHandler()); t.run(); } } class RunHandler { public void run() { Scanner in = new Scanner(System.in); int x = in.nextInt(); System.out.println("run"); } }
输入格式:
输入一个整数x。
输出格式:
输出x行,每行一个字符串“run”。
输入样例:
4
输出样例:
run
run
run
run
import java.util.*;
public class Main {
public static void main(String[] args) {
Thread t = new Thread(new RunHandler());
t.run();
}
}
class RunHandler implements Runnable {
public void run() {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
for(int i=0;i<x;i++)
System.out.println("run");
}
}