如果需要线程暂缓执行,那么可以使用线程的休眠处理
毫秒级休眠
public static void sleep (long millis) throws InterruptedException
纳秒级休眠
public static void sleep (long millis, int nanos) throws InterruptedException
在进行休眠的时候可能会产生中断异常,而InterruptedException是Exception的子类,必须进行处理。
休眠处理(休眠时间一到,程序会自动执行)
public class TestThread {
public static void main(String[] args) {
new Thread(() -> {
for (int x = 0; x < 10; x++) {
System.out.println(Thread.currentThread().getName() + "、x = " + x);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, "线程对象").start();
}
}
结果如下
多个线程休眠处理(这时产生五个线程对象,执行方法体相同,但执行顺序不同)
public class TestThread {
public static void main(String[] args) {
for (int num = 0; num < 5; num++) {
new Thread(() -> {
for (int x = 0; x < 10; x++) {
System.out.println(Thread.currentThread().getName() + "、x = " + x);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, "线程对象 - " + num).start();
}
}
}
结果如下