线程休眠

线程休眠

sleep(时间) 指定当前线程阻塞的毫秒数

sleep存在异常InterruptedException

sleep时间达到后线程进入就绪状态

sleep可以模拟网络延时、计时器等

每个对象都有一个锁,sleep不会释放锁

代码

package com.example.multi_thread;

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

public class TestSleep {


    public static void main(String[] args) throws InterruptedException {
        // 计时器
        TestSleep testSleep = new TestSleep();
        testSleep.tenDown();

        // 时间显示
        Date currenttime = new Date(System.currentTimeMillis());
        while (true) {
            System.out.println(new SimpleDateFormat("HH:mm:ss").format(currenttime));
            Thread.sleep(1000);
            currenttime = new Date(System.currentTimeMillis());
        }
    }

    public void tenDown() throws InterruptedException {
        for (int i = 10; i > 0; i--) {
            System.out.println(i);
            Thread.sleep(1000);
        }
    }
}
posted @ 2021-11-11 16:09  Oh,mydream!  阅读(25)  评论(0编辑  收藏  举报