十四、线程休眠(14、 Thread sleep)

  • sleep(时间)指定当前线程阻塞的毫秒数;
  • sleep存在异常InterruptedException;
  • sleep时间达到后线程进入就绪状态;
  • sleep可以模拟网络延时,倒计时等。
  • 每一个对象都有一个锁,sleep不会释放锁;

倒计时Demo:

public class ThreadSleep2 {

    public static void main(String[] args) {
        int i =10;
        try {
            cutDown(i);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    //倒计时
    public static void cutDown(int i) throws InterruptedException {
        while (true){
            Thread.sleep(1000);
            if (i>=0){
                System.out.println(i--);
            }else break;
        }
    }
    
}
————————
  • Sleep specifies the number of milliseconds that the current thread is blocked;
  • sleep存在异常InterruptedException;
  • After the sleep time reaches, the thread enters the ready state;
  • Sleep can simulate network delay, countdown, etc.
  • Each object has a lock, and sleep will not release the lock;

Countdown Demo:

public class ThreadSleep2 {

    public static void main(String[] args) {
        int i =10;
        try {
            cutDown(i);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    //倒计时
    public static void cutDown(int i) throws InterruptedException {
        while (true){
            Thread.sleep(1000);
            if (i>=0){
                System.out.println(i--);
            }else break;
        }
    }
    
}