Java sleep()睡眠/等待用法

try {		//延时1秒,模拟时钟秒
	Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
	e.printStackTrace();
}

sleep(),里面参数为毫秒单位,1s == 1000ms

实例,模拟时钟:

class Display{
	private int value = 0;
	private	int limit = 0;
	
	public Display(int limit) {
		this.limit = limit;
	}
	
	public void increase() {
		value ++;
		if (value == limit) {
			value = 0;
		}
	}
	
	public int getValue() {
		return value; 
	}
}

public class Clock {   
	private Display hour = new Display(24);
	private Display minute = new Display(60); 
	
	public void start(){
		while (true) {
			minute.increase();
			if (minute.getValue() == 0) {
				hour.increase();
			}
			System.out.printf("%02d:%02d\n", hour.getValue(), minute.getValue());
			try {		//延时1秒,模拟时钟秒
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Clock clock = new Clock();
		clock.start();
	}

}

实例演示:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43347550/article/details/105789855