文章目录

  • 一、sleep()是什么?
  • 测量时间



一、sleep()是什么?

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

你可以让程序休眠一毫秒的时间或者到您的计算机的寿命长的任意段时间。例如,下面的程序会休眠3秒:

import java.util.*;
public class SleepDemo {
   public static void main(String args[]) {
      try { 
         System.out.println(new Date( ) + "\n"); 
         Thread.sleep(1000*3);   // 休眠3秒
         System.out.println(new Date( ) + "\n"); 
      } catch (Exception e) { 
          System.out.println("有意外!"); 
      }
   }
}

以上实例编译运行结果如下:

Thu Jan 14 17:37:16 CST 2021

Thu Jan 14 17:37:19 CST 2021

测量时间

下面的一个例子表明如何测量时间间隔(以毫秒为单位):

实例

import java.util.*; 
public class DiffDemo { 
   public static void main(String args[]) {
      try {
         long start = System.currentTimeMillis( );
         System.out.println(new Date( ) + "\n");
         Thread.sleep(5*60*10);
         System.out.println(new Date( ) + "\n");
         long end = System.currentTimeMillis( );
         long diff = end - start;
         System.out.println("间隔是 : " + diff);
      } catch (Exception e) {
         System.out.println("有意外!");
      }
   }
}

运行实例 »
以上实例编译运行结果如下:

Thu Jan 14 17:41:55 CST 2021

Thu Jan 14 17:41:58 CST 2021

间隔是 : 3036