1、sleep()介绍
sleep()定义在Thread.java中。sleep()的作用是让当前线程休眠,即当前线程会从“运行状态”进入到“休眠(阻塞)状态”。sleep()会指定休眠时间,线程休眠时间会大于/等于该休眠时间;在线程被重新唤醒时,它会由“阻塞状态”变为“就绪状态”,从而等待CPU的调度执行
2、sleep()示例
class ThreadA extends Thread { public ThreadA(String name) { super(name); } public synchronized void run() { try { for(int i = 0;i < 10;i++) { System.out.printf("%s [%d]: %d ",this.getName(),this.getPriority(),i); if(i%4 == 0) Thread.sleep(100); } } catch (InterruptedException e) { e.printStackTrace(); } } } public class SleepTest { public static void main(String[] args) { ThreadA t1 = new ThreadA("t1"); t1.start(); } }
运行结果:
t1 [5]: 0 t1 [5]: 1 t1 [5]: 2 t1 [5]: 3 t1 [5]: 4 t1 [5]: 5 t1 [5]: 6 t1 [5]: 7 t1 [5]: 8 t1 [5]: 9
结果说明:
一个简单的小程序,当i%4==0的时候,线程休眠100ms
3、sleep()与wait()的比较
wait()的作用是让当前线程由“运行状态”进入“等待状态”的同时,也会释放同步锁。而sleep()的作用是让当前线程由“运行状态”进入“休眠状态”。但是sleep()不会释放同步锁
示例:
public class SleepLockTest { private static Object obj = new Object(); public static void main(String[] args) { ThreadA t1 = new ThreadA("t1"); ThreadA t2 = new ThreadA("t2"); t1.start(); t2.start(); } static class ThreadA extends Thread { public ThreadA(String name) { super(name); } public void run() { synchronized (obj) { try { for(int i = 0;i <10;i++) { System.out.printf("%s: %d ",this.getName(),i); if(i%4 == 0) Thread.sleep(100); } } catch (InterruptedException e) { e.printStackTrace(); } } } } }
运行结果:
t1: 0 t1: 1 t1: 2 t1: 3 t1: 4 t1: 5 t1: 6 t1: 7 t1: 8 t1: 9 t2: 0 t2: 1 t2: 2 t2: 3 t2: 4 t2: 5 t2: 6 t2: 7 t2: 8 t2: 9
结果说明:
主线程中启动了两个线程t1和t2。t1和t2在run()会引用同一个同步锁,synchronized(obj)。在t1运行的过程中,虽然调用了sleep(),但是t2无法获取CPU执行权,因为t1没有释放锁