一、API简介

Thread.sleep()是Thread类的一个静态方法,使当前线程休眠,进入阻塞状态(暂停执行),如果线程在睡眠状态被中断,将会抛出IterruptedException中断异常。。主要方法如下:

【a】sleep(long millis)  线程睡眠 millis 毫秒

【b】sleep(long millis, int nanos)  线程睡眠 millis 毫秒 + nanos 纳秒

Api文档:

二、使用方法

注意:在哪个线程里面调用sleep()方法就阻塞哪个线程。

public class SleepDemo {
    public static void main(String[] args) throws InterruptedException {
        Process process = new Process();
        Thread thread = new Thread(process);
        thread.setName("线程Process");
        thread.start();

        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "-->" + i);
            //阻塞main线程,休眠一秒钟
            Thread.sleep(1000);
        }
    }
}

/**
 * 线程类
 */
class Process implements Runnable {

    @Override
    public void run() {

        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "-->" + i);

            //休眠一秒钟
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}

执行结果:main线程执行一次之后休眠一秒钟,让出cpu,此时Process线程执行一次然后又休眠一秒,依次执行。

三、示例

下面以一个倒计时的功能来进一步说明sleep()方法的使用:

/**
 * @Description: 线程休眠Sleep()方法
 * @Author: weishihuai
 * @Date: 2018/11/11 21:31
 * <p>
 * 1. 注意:sleep()方法使用的位置,如果使用在main线程执行代码中,则阻塞的是main线程。如果在其他线程执行的代码中,则阻塞的是执行这些代码的线程
 * 2. 案例: 倒计时功能
 */
public class TestSleepThread {
    public static void main(String[] args) throws InterruptedException {
        countDown(10000);
    }

    /**
     * 倒计时方法
     *
     * @param mills 倒计时开始的时间距离当前时间多少毫秒
     */
    public static void countDown(long mills) {
        Date endDate = new Date(System.currentTimeMillis() + mills);
        long endTime = endDate.getTime();

        while (true) {
            System.out.println(new SimpleDateFormat("hh:mm:ss").format(endDate));
            //下一秒时间
            endDate = new Date(endDate.getTime() - 1000);
            //休眠一秒钟
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (endTime - endDate.getTime() > mills) {
                break;
            }
        }
    }

}

执行结果:

四、注意问题

【a】sleep()方法是Thread类的静态方法,如果调用线程对象.sleep()方法并不是该线程就休眠,反正在哪一个线程里面执行了sleep()方法哪一个线程就休眠。

【b】线程睡眠到期自动苏醒,并返回到可运行状态(就绪),不是运行状态。

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐