Sleep-线程休眠

sleep 存在异常InterruptedException

每一个对象都有一把锁,sleep不会释放锁。   (线程同步)

1.模拟延时

try{
 Thread.sleep(millis:100);
 }catch(InterruptedException e){
    e.printStackTrace();
 }
  SOP("")
}

2.模拟倒计时

public void tenDown() throws InterruptedException{
       int num=10;
	   while(true){
	       Thread.sleep(millis:1000);
		   System.out.println(num--);
		   if(num<=0){
		   break;
		   }
	    }
}

3.打印当前时间

public static void main(String[] args){
 //打印当前系统时间
 Date startTime = new Date(System.currentTimeMills());//获取当前系统时间 
 while(true){
       try{
	       Thread.sleep(millis:1000);
		   System.out.println(new SimpleDateFormat(pattern:"HH:mm:ss").format(startTime));
           startTime = new Date(System.currentTimeMills());//更新当前时间
		   }catch(InterruptedException e){
		      e.printStackTrace();
		   }
		 }
 }

  

 

posted @ 2022-06-26 18:36  小布丁dd  阅读(17)  评论(0)    收藏  举报