美文网首页SpringFramework
脑壳疼:Java Object.wait() jvm的bug

脑壳疼:Java Object.wait() jvm的bug

作者: 猿生进阶 | 来源:发表于2020-11-23 17:38 被阅读0次
image

在使用java线程的时候,经常会用到wait方法,如果在调用wait方法的时候被中断,jvm会捕获这个中断不断调用wait 指令

这时候即使你使用interrupt 发法来中断都是没有用的.

需要对wait方法做一些封装,捕获异常,然后停止执行它

public  static  void  wait(Object  obj) {

             boolean  interrupted =  true ;

             while (interrupted) { 
                      interrupted =false ;
                      try{ 
                                obj.wait();
                         }
                     catch (InterruptedException e)  {
                              interrupted =true ;
                     } 
             } 
     }

    public  static  void  wait ( Object obj,inttimeout ){
          boolean  interrupted =true;
          longstartTime = System.currentTimeMillis() ;
          int  sleepTimeout = timeout;
         
         while ( interrupted)  {
                  interrupted =false;
                  try { 
                        obj.wait(sleepTimeout);
                 }
                 catch (  InterruptedException e) {
                            interrupted =true ;
                            long now = System.currentTimeMillis();
                            sleepTimeout -= now - startTime; 
                            startTime = now;
                            if ( sleepTimeout <0 ) {
                                     interrupted =false;
                            }
                 }
        }
 }

相关文章

网友评论

    本文标题:脑壳疼:Java Object.wait() jvm的bug

    本文链接:https://www.haomeiwen.com/subject/ggeviktx.html