Java Thread sleep()方法

java.lang.Thread.sleep(long millis) 方法使当前执行指定线程休眠的毫秒数,受制于精度和系统计时器和调度程序精度。

1 语法

public static void sleep(long millis) throws InterruptedException

2 参数

millis:这是以毫秒为单位的休眠时间。

3 返回值

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.lang.Thread.sleep(long millis) 方法的例子
 */
import java.lang.*;

public class Demo implements Runnable {

    Thread t;

    public void run() {
        for (int i = 10; i < 13; i++) {

            System.out.println(Thread.currentThread().getName() + "  " + i);
            try {
                // thread to sleep for 1000 milliseconds
                Thread.sleep(1000);
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Thread t = new Thread(new Demo());
        // this will call run() function
        t.start();

        Thread t2 = new Thread(new Demo());
        // this will call run() function
        t2.start();
    }
}

输出结果为:

Thread-0  10
Thread-1  10
Thread-0  11
Thread-1  11
Thread-1  12
Thread-0  12

热门文章

优秀文章