Java 休眠

        sleep()使当前线程进入停滞状态(阻塞当前线程),让出CPU的使用、目的是不让当前线程独自霸占该进程所获的CPU资源,以留一定时间给其他线程执行的机会。

实例1:

import java.util.Date;

public class Test{
    public static void main(String args[]) {
        try {
            for(int i = 0; i < 10; ++i){
                System.out.println(new Date() + "\n");
                Thread.sleep(1000 * 2);   // 休眠2秒
            }
        }catch (Exception e) {
            System.out.println("Got an exception!");
        }
    }
}

结果展示1:

Mon Jan 13 15:33:49 CST 2020

Mon Jan 13 15:33:51 CST 2020

Mon Jan 13 15:33:53 CST 2020

Mon Jan 13 15:33:55 CST 2020

Mon Jan 13 15:33:57 CST 2020

Mon Jan 13 15:33:59 CST 2020

Mon Jan 13 15:34:01 CST 2020

Mon Jan 13 15:34:03 CST 2020

Mon Jan 13 15:34:05 CST 2020

Mon Jan 13 15:34:07 CST 2020

实例2:

import java.util.Date;

public class Test{
    public static void main(String args[]) {
        long start = System.currentTimeMillis( );
        try {
            for(int i = 0; i < 5; ++i){
                System.out.println(new Date() + "\n");
                Thread.sleep(1000 * 2);   // 休眠2秒
            }
        }catch (Exception e) {
            System.out.println("Got an exception!");
        }
        long end = System.currentTimeMillis( );
        long speedTime = (end - start)/1000;
        System.out.println("Run the program, take the time: " + speedTime + " s");
    }
}

结果展示2:

Mon Jan 13 15:46:09 CST 2020

Mon Jan 13 15:46:11 CST 2020

Mon Jan 13 15:46:13 CST 2020

Mon Jan 13 15:46:15 CST 2020

Mon Jan 13 15:46:17 CST 2020

Run the program, take the time: 10 s
发布了147 篇原创文章 · 获赞 24 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_36535820/article/details/103958867