天天看點

線程基礎知識點 notify()

wait()  , notify()  必須處在 目前對象螢幕(鎖對象) 同步塊内調用,否則會爆  current thread not owner; 即:

IllegalMonitorStateException.

notify()  喚醒的線程也得與次對象螢幕上的線程去競争所有權(也包括目前調用notify() 自身線程在釋放鎖後也會去競争)。

隊列緩沖區:  用Condition 線程通信機制 多路通信實作。 可參考: JDK幫助文檔 Condition類

class BoundedBuffer {
   final Lock lock = new ReentrantLock();
   final Condition notFull  = lock.newCondition(); 
   final Condition notEmpty = lock.newCondition(); 

   final Object[] items = new Object[100];
   int putptr, takeptr, count;

   public void put(Object x) throws InterruptedException {
     lock.lock();
     try {
       while (count == items.length) 
         notFull.await();
       items[putptr] = x; 
       if (++putptr == items.length) putptr = 0;
       ++count;
       notEmpty.signal();
     } finally {
       lock.unlock();
     }
   }

   public Object take() throws InterruptedException {
     lock.lock();
     try {
       while (count == 0) 
         notEmpty.await();
       Object x = items[takeptr]; 
       if (++takeptr == items.length) takeptr = 0;
       --count;
       notFull.signal();
       return x;
     } finally {
       lock.unlock();
     }
   } 
 }
      
代理緩存:  用 ReadWriteLock 讀寫鎖機制實作, 參考JDK  ReentrantReadWriteLock類         
class CachedData {
   Object data;
   volatile boolean cacheValid;
   ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

   void processCachedData() {
     rwl.readLock().lock();
     if (!cacheValid) {
        // upgrade lock manually
        rwl.readLock().unlock();   // must unlock first to obtain writelock
        rwl.writeLock().lock();
        if (!cacheValid) { // recheck
          data = ...
          cacheValid = true;
        }
        // downgrade lock
        rwl.readLock().lock();  // reacquire read without giving up write lock
        rwl.writeLock().unlock(); // unlock write, still hold read
     }

     use(data);
     rwl.readLock().unlock();
   }
 }