10.0、Java多线程——线程休眠
sleep(时间)指定当前线程阻塞的毫秒数;
sleep存在异常InterruptedException;
sleep时间达到后线程进入就绪状态;
sleep可以模拟网络演示,倒计时等;
每一个对象都有一个锁,sleep不会释放锁
接下里写一个线程休眠的例子——倒计时,代码如下所示:
TestSleep.java文件:
package com.hkl.state;
public class TestSleep {
public static void main(String[] args) throws InterruptedException {
tenDown();
}
//倒计时
public static void tenDown() throws InterruptedException {
int num = 10;
while (num >= 0) {
Thread.sleep(1000);
System.out.println(num--);
}
}
}
再写一个获取系统当前时间的例子,代码如下所示:
TestSleep.java文件:
package com.hkl.state;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSleep {
public static void main(String[] args) throws InterruptedException {
Date startTime = new Date(System.currentTimeMillis());
while (true) {
System.out.println(new SimpleDateFormat("HH:MM:ss").format(startTime));
Thread.sleep(1000);
startTime = new Date(System.currentTimeMillis());
}
}
}
不管是倒计时还是获取当前时间,线程都是每秒执行一次,因为我们加了Thread.sleep(1000)休眠一秒