线程休眠sleep
- sleep(时间)指定当前线程阻塞的毫秒数;
- sleep存在异常InterruptedException;
- sleep时间达到后线程进入就绪状态;
- sleep可以模拟网络延时,倒计时等。;
- 每一个对象都有一个锁,sleep不会释放锁;
使用Thread.sleep(millis ***);方法实现,会存在一个InterruptedException
异常。
以下列举倒计时和打印当前时间为例
编写一个倒计时器
package com.thread;
import java.util.Scanner;
//模拟倒计时
public class TestSleep1 {
public void timeDown(int time) throws InterruptedException {
while (true){
Thread.sleep(1000);
System.out.println(time--);
if (time <= 0){
System.out.println("计时结束!");
break;
}
}
}
public static void main(String[] args) {
System.out.print("输入倒计时秒数:");
Scanner scanner = new Scanner(System.in);
int time = scanner.nextInt();
try {
new TestSleep1().timeDown(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
模拟打印当前时间
package com.thread;
import java.text.SimpleDateFormat;
import java.util.Date;
//模拟打印当前时间
public class TestSleep2 {
public void time(){
Date date = new Date(System.currentTimeMillis());
while (true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
date = new Date(System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new TestSleep2().time();
}
}