天天看点

线程基础知识点 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();
   }
 }