public class WithSleep {
public static void main(String[] args) throws InterruptedException {
Runnable runnable = () -> {
int num = 0;
System.out.println("begin");
try {
while (num <= 10000) {
if (num % 100 == 0) System.out.println(num);
num++;
Thread.sleep(10); // 1
}
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Thread thread = new Thread(runnable);
thread.start();
System.out.println(Thread.currentThread().getName());
Thread.sleep(5000); // 2
thread.interrupt();
}
}
执行情况
main
begin
0
100
200
300
400
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.hanxunliang.stopthreads.WithSleep.lambda$main$0(WithSleep.java:19)
at java.lang.Thread.run(Thread.java:748)
老师,我有两个问题:
start()
在打印语句之前执行,为什么打印语句却在先执行?sleep()
和 2处 sleep()
的执行情况是怎样的?