Java 中 sleep() 和 wait() 的区别 🎉 两者区别 对于 sleep() 方法,我们首先要知道该方法属于 Thread 类中。而 wait() 方法则属于 Object 类中的。 sleep() 方法导致了程序暂停执行指定的时间,让出cpu该其他线程,但是他的监控状态依然保持着,当指定的时间到了又会自动恢复运行状态。 调用 sleep() 方法过程中,线程不会释放对象锁。 调用 wait() 方法的时候,线程会放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象调用 notify() 方法后本线程才进入对象锁定池准备获取对象锁进入运行状态。 🎉 举例说明 代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 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 sleep...." ); 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!!!" ); } } } }
运行结果:
1 2 3 4 5 6 7 8 enter thread1... thread1 is waiting... enter thread2.... thread2 is sleep.... thread2 is going on.... thread2 is over!!! thread1 is going on .... thread1 is over!!!
如果注释掉下面这行代码:
运行结果变为:
1 2 3 4 5 6 enter thread1... thread1 is waiting... enter thread2.... thread2 is sleep.... thread2 is going on.... thread2 is over!!!
且程序一直处于挂起状态。
经过上面这段代码演示我相信大家会更容易的理解 sleep() 和 wait() 的区别。