×

分析在java中sleep和wait的不同

消耗积分:2 | 格式:rar | 大小:1.5 MB | 2017-09-27

分享资料个

  对于sleep()方法,我们首先要知道该方法是属于Thread类中的。而wait()方法,则是属于Object类中的。

  sleep()方法导致了程序暂停执行指定的时间,让出cpu该其他线程,但是他的监控状态依然保持者,当指定的时间到了又会自动恢复运行状态。

  在调用sleep()方法的过程中,线程不会释放对象锁。

  而当调用wait()方法的时候,线程会放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象调用notify()方法后本线程才进入对象锁定池准备

  获取对象锁进入运行状态。

  什么意思呢?

  举个列子说明:

  /** * */packagecom.b510.test; /** * java中的sleep()和wait()的区别 *@authorHongten Java学习交流QQ群:589809992 我们一起学Java! *@date2013-12-10 */publicclassTestD{publicstaticvoidmain(String[] args) { newThread( newThread1()).start();try{ Thread.sleep( 5000); } catch(Exception e) { e.printStackTrace(); } newThread(newThread2()).start(); }privatestaticclassThread1implementsRunnable{@Overridepublicvoidrun(){synchronized(TestD.class) { System.out.println( “enter thread1.。。”); System.out.println(“thread1 is waiting.。。”); try{ //调用wait()方法,线程会放弃对象锁,进入等待此对象的等待锁定池TestD.class.wait(); } catch(Exception e) { e.printStackTrace(); } System.out.println(“thread1 is going on 。。.。”); System.out.println( “thread1 is over!!!”); } } }privatestaticclassThread2implementsRunnable{@Overridepublicvoidrun(){synchronized(TestD.class) { System.out.println( “enter thread2.。。.”); System.out.println(“thread2 is sleep.。。.”); //只有针对此对象调用notify()方法后本线程才进入对象锁定池准备获取对象锁进入运行状态。TestD.class.notify(); //==================//区别//如果我们把代码:TestD.class.notify();给注释掉,即TestD.class调用了wait()方法,但是没有调用notify()//方法,则线程永远处于挂起状态。try{ //sleep()方法导致了程序暂停执行指定的时间,让出cpu该其他线程,//但是他的监控状态依然保持者,当指定的时间到了又会自动恢复运行状态。//在调用sleep()方法的过程中,线程不会释放对象锁。Thread.sleep( 5000); }catch(Exception e) { e.printStackTrace(); } System.out.println( “thread2 is going on.。。.”); System.out.println( “thread2 is over!!!”); } } } }

  运行效果:

  enter thread1.。。 thread1 iswaiting.。。 enter thread2.。。. thread2 issleep.。。. thread2 isgoingon.。。. thread2 isover!!! thread1 isgoing on.。。. thread1 isover!!!

  如果注释掉代码:

  1TestD .class.notify() ;

  运行效果:

  enter thread1.。。 thread1 iswaiting.。。 enter thread2.。。. thread2 issleep.。。. thread2 isgoingon.。。. thread2 isover!!!

  且程序一直处于挂起状态。返回

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

评论(0)
发评论

下载排行榜

全部0条评论

快来发表一下你的评论吧 !