Thread sleep-Sleep

Thread sleep

  • Sleep (time) specifies the number of milliseconds that the current thread is blocked;
  • Sleep has an exception InterruptedException;
  • After the Sleep time is reached, the thread enters the ready state;
  • Sleep can simulate network delay, countdown, etc.
  • Every object has a lock, Sleep will not release the lock

Case

package Thread;


import java.sql.SQLOutput;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestSleep {
    
    

    public static void main(String[] args) throws InterruptedException {
    
    
        //tenDown();
        Time();
    }

    //模拟倒计时
    public static  void tenDown() throws InterruptedException {
    
    
        int num=10;
        while (true){
    
    
            Thread.sleep(1000);
            System.out.println(num--);
            if (num<=0){
    
    
                break;
            }
        }
    }

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

Guess you like

Origin blog.csdn.net/qq_45162683/article/details/111590052