Java 线程睡眠期间输出问题及解决方法
public class SleepyCounter { public static void main(String[] args) { Thread sleepyCounter = new Thread(new Runnable() { public void run() { for (int i = 10; i <= 500; i++) { System.out.print(i); System.out.print(' The thread sleeps 5 ms\n'); try { Thread.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } } } }); sleepyCounter.start(); } }
为什么没有输出'The thread sleeps 5 ms'内容:在给定的代码中,输出语句 'The thread sleeps 5 ms' 被放置在了 sleep() 方法的后面,因此在每次线程睡眠结束后才会被执行。这意味着输出语句会在每个数字输出之后才会执行,而不是在睡眠期间。如果希望输出语句在睡眠期间执行,可以将其移到 sleep() 方法的前面。以下是修改后的代码:
public class SleepyCounter {
public static void main(String[] args) {
Thread sleepyCounter = new Thread(new Runnable() {
public void run() {
for (int i = 10; i <= 500; i++) {
System.out.print(i);
System.out.print(' The thread sleeps 5 ms\n');
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
sleepyCounter.start();
}
}
这样就可以在每次线程睡眠期间输出 'The thread sleeps 5 ms'。
原文地址: http://www.cveoy.top/t/topic/pjeq 著作权归作者所有。请勿转载和采集!