[Java] Java I/O 的工作机制 →→→→→进入此内容的聊天室

来自 , 2020-10-23, 写在 Java, 查看 131 次.
URL http://www.code666.cn/view/25df35de
  1. class AsyncResult implements IAsyncResult{
  2.     private byte[] result_;
  3.     private AtomicBoolean done_ = new AtomicBoolean(false);
  4.     private Lock lock_ = new ReentrantLock();
  5.     private Condition condition_;
  6.     private long startTime_;
  7.     public AsyncResult(){        
  8.         condition_ = lock_.newCondition();// 创建一个锁
  9.         startTime_ = System.currentTimeMillis();
  10.     }    
  11.  /*** 检查需要的数据是否已经返回,如果没有返回阻塞 */
  12.  public byte[] get(){
  13.         lock_.lock();
  14.         try{
  15.             if (!done_.get()){condition_.await();}
  16.         }catch (InterruptedException ex){
  17.             throw new AssertionError(ex);
  18.         }finally{lock_.unlock();}
  19.         return result_;
  20.  }
  21.  /*** 检查需要的数据是否已经返回 */
  22.     public boolean isDone(){return done_.get();}
  23.  /*** 检查在指定的时间内需要的数据是否已经返回,如果没有返回抛出超时异常 */
  24.     public byte[] get(long timeout, TimeUnit tu) throws TimeoutException{
  25.         lock_.lock();
  26.         try{            boolean bVal = true;
  27.             try{
  28.                 if ( !done_.get() ){
  29.            long overall_timeout = timeout - (System.currentTimeMillis() - startTime_);
  30.                     if(overall_timeout > 0)// 设置等待超时的时间
  31.                         bVal = condition_.await(overall_timeout, TimeUnit.MILLISECONDS);
  32.                     else bVal = false;
  33.                 }
  34.             }catch (InterruptedException ex){
  35.                 throw new AssertionError(ex);
  36.             }
  37.             if ( !bVal && !done_.get() ){// 抛出超时异常
  38.                 throw new TimeoutException("Operation timed out.");
  39.             }
  40.         }finally{lock_.unlock();      }
  41.         return result_;
  42.  }
  43.  /*** 该函数拱另外一个线程设置要返回的数据,并唤醒在阻塞的线程 */
  44.     public void result(Message response){        
  45.         try{
  46.             lock_.lock();
  47.             if ( !done_.get() ){                
  48.                 result_ = response.getMessageBody();// 设置返回的数据
  49.                 done_.set(true);
  50.                 condition_.signal();// 唤醒阻塞的线程
  51.             }
  52.         }finally{lock_.unlock();}        
  53.     }    
  54.  }//源代码片段来自云代码http://yuncode.net
  55.                        

回复 " Java I/O 的工作机制"

这儿你可以回复上面这条便签

captcha