答案出错 修改一下上面的代码
时间: 2024-03-10 15:44:31 浏览: 22
非常抱歉,可能是我在编写代码时出现了错误。请尝试以下修改后的代码:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
CountdownRunnable r = new CountdownRunnable(N);
Thread t = new Thread(r);
t.start();
}
}
class CountdownRunnable implements Runnable {
private int N; // 记录剩余的数字
public CountdownRunnable(int N) {
this.N = N;
}
public void run() {
while (N > 0) {
System.out.println("剩余数:" + N);
N--;
try {
Thread.sleep(500); // 线程休眠0.5秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
该程序中,我们修改了创建线程的方式,先创建 CountdownRunnable 对象 r,然后通过该对象创建一个新线程 t,并启动该线程。这样可以保证线程的任务与线程本身是一一对应的,从而避免由于多线程竞争导致的数据错误。另外,我们还将 Thread.sleep() 方法放在了 while 循环内部,以便每隔0.5秒执行一次剩余数的打印输出。