Java 线程计数器代码分析与优化
这段代码有两个问题:
-
在run方法的定义中,缺少圆括号。应该是'public void run()'而不是'public void run'。
-
在run方法中,缺少线程的休眠或暂停操作,导致数字连续输出,无法观察到线程的执行过程。可以通过在循环中添加'Thread.sleep()'方法来使线程休眠一段时间,例如'Thread.sleep(1000)'表示线程暂停1秒。 修改后的代码如下:
public class Counter extends Thread {
public void run() {
for(int i=10; i<=500; i++) {
System.out.print(i + " ");
try {
Thread.sleep(1000); // 线程休眠1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Counter().start();
}
}
AI 优化版
原文地址:https://www.cveoy.top/t/topic/pi1w 著作权归作者所有。请勿转载和采集!