sleep()与wait()的差别(java笔记-多线程)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sleep()与wait()的差别(java笔记-多线程)相关的知识,希望对你有一定的参考价值。
1 package test; 2 3 public class test1 { 4 5 public static void main(String[] args) { 6 7 new Thread(new thread1()).start(); 8 try { 9 Thread.sleep(5000); 10 } catch (InterruptedException e) { 11 12 e.printStackTrace(); 13 } 14 new Thread(new thread2()).start(); 15 16 } 17 } 18 19 class thread1 implements Runnable { 20 21 @Override 22 public void run() { 23 24 synchronized (test1.class) { 25 System.out.println("here is thread1"); 26 System.out.println("thread1 is waiting"); 27 28 try { 29 test1.class.wait();// 调用wait,会释放线程锁,进入等待锁定池,直到調用notify方法唤醒,再次进入对象锁定池准备获取对象锁进入运行状态。 30 31 } catch (InterruptedException e) { 32 33 e.printStackTrace(); 34 } 35 System.out.println("thread1 is going"); 36 System.out.println("thread1 is over"); 37 } 38 } 39 } 40 41 class thread2 implements Runnable { 42 43 @Override 44 public void run() { 45 // 46 synchronized (test1.class) { 47 System.out.println("here is thread2"); 48 System.out.println("thread2 is sleeping"); 49 test1.class.notify(); 50 try { 51 Thread.sleep(4000);// 调用sleep,会等待相应时间,等待时线程锁不释放,时间到了会进入运行状态; 52 System.out.println("thread2 is going"); 53 System.out.println("thread2 is over"); 54 } catch (InterruptedException e) { 55 e.printStackTrace(); 56 } 57 } 58 } 59 }
运行结果:
here is thread1
thread1 is waiting
here is thread2
thread2 is sleeping
thread2 is going
thread2 is over
thread1 is going
thread1 is over
注释掉49行的“test1.class.notify();”
程序会一直处于挂起状态:
here is thread1
thread1 is waiting
here is thread2
thread2 is sleeping
thread2 is going
thread2 is over
sleep()方法属于Thread类;wait()方法属于Object类。
在调用sleep()方法的过程中,线程不会释放对象锁。而当调用wait()方法的时候,线程会放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象调用notify()方法后本线程才进入对象锁定池准备。
感谢大神 Hongten;
以上是关于sleep()与wait()的差别(java笔记-多线程)的主要内容,如果未能解决你的问题,请参考以下文章
诺禾:诺禾通俗易懂的告诉你java多线程中wait和sleep的区别