欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Thread() sleep()

程序员文章站 2022-06-21 10:53:28
...

照着官方手册:

public class SleepMessages {
    public static void main(String args[])
            throws InterruptedException {   //当sleep过程中有其他线程打断了当前线程,可以抛出这个异常。
        String importantInfo[] = {
                "Mares eat oats",
                "Does eat oats",
                "Little lambs eat ivy",
                "A kid will eat ivy too"
        };

        for (int i = 0;
             i < importantInfo.length;
             i++) {
            //Pause for 4 seconds
            Thread.sleep(4000);  //单位millis 千分之一秒
            //Print a message
            System.out.println(importantInfo[i]);
        }
    }
}

结果:每隔一段时间打印一行,直到四行打印完毕,当前线程由于被sleep()以后,所以才会断断续续执行。

Mares eat oats
Does eat oats
Little lambs eat ivy
A kid will eat ivy too

来看sleep()方法:
Thread() sleep()
sleep是一个native方法。native方法怎么实现不在讨论范围之内。

/**
     * Causes the currently executing thread to sleep (temporarily cease
     * execution) for the specified number of milliseconds, subject to
     * the precision and accuracy of system timers and schedulers. The thread
     * does not lose ownership of any monitors.
     *
     * @param  millis
     *         the length of time to sleep in milliseconds
     *
     * @throws  IllegalArgumentException
     *          if the value of {@code millis} is negative
     *
     * @throws  InterruptedException
     *          if any thread has interrupted the current thread. The
     *          <i>interrupted status</i> of the current thread is
     *          cleared when this exception is thrown.
     */
    public static native void sleep(long millis) throws InterruptedException;

Java官方英文手册https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html

相关标签: 线程 thread