1、wait()来自于Object类而sleep来自于Thread类
2、sleep没有释放锁,但是wait释放了锁(使得其他线程可以使用同步控制块或者方法锁)
3、wait,notify和notifyAll只能在同步控制方法或者同步控制块使用,而sleep能在各个地方使用
4、sleep必须捕获异常,但是其它wait不用
5、sleep让一个线程睡眠,等待一段时间后,自动醒来进入可运行状态,不会马上进入运行状态,因为线程调度机制恢复线程也需要时间。如果调用interrup方法,则会抛出InterruptedException。如果不捕获这个异常,那么会进入TERMINATED状态。如果捕获这个异常,那么可以在catch中继续执行后面的代码。
6、sleep是静态方法,只会让当前线程sleep,t.sleep()并不会让t进入sleep
如果线程并不处于wait,sleep,join状态时,调用interrupt方法线程不会抛出InterruptedException。
wait和notify必须在synchronized方法或者block中。
二、Code便于理解
package threads.waitandsleep; /** * Created by adrian.wu on 2019/6/1. */ public class TestD { public static void main(String[] args) { new Thread(new Thread1()).start(); try { Thread.sleep(5000); }catch (Exception e){ e.printStackTrace(); } new Thread(new Thread2()).start(); } public static class Thread1 implements Runnable { @Override public void run() { synchronized (TestD.class) { System.out.println("enter thread1...."); System.out.println("thread1 is waiting"); try { TestD.class.wait(); } catch (Exception e) { e.printStackTrace(); } } System.out.println("thread1 is going on...."); System.out.println("thread1 is over!!"); } } public static class Thread2 implements Runnable { @Override public void run() { synchronized (TestD.class) { System.out.println("enter thread2...."); System.out.println("thread2 is waiting"); TestD.class.notify(); } try { Thread.sleep(5000); }catch (Exception e){ e.printStackTrace(); } System.out.println("thread2 is going on...."); System.out.println("thread2 is over!!"); } } }
结果:
enter thread1.... thread1 is waiting enter thread2.... thread2 is waiting thread1 is going on.... thread1 is over!! thread2 is going on.... thread2 is over!!
解释:
wait()会释放锁,sleep()不会。也就是说wait 需要notify去唤醒。而sleep()并不会。只要当sleep时间到了就会自动执行下面的过程,但是会让出CPU线程。