首页 > 代码库 > sleep()与wait()的差别(java笔记-多线程)
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笔记-多线程)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。