java lock的机制

Java.util.cocurrent.lock

         是一个能够更好的使用锁机制的新框架。

         主要技术要点:

Wait           notify            notifyAll

         condition lock ReadWriteLock来实现锁机制

         Lock.cock(): 获取锁

 

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();           à try 里面的要

       items[putptr] = x;                     活得lock后才能执行

       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--------------:ReadWriteLock 维护了一对相关的,一个用于只读操作,另一个用于写入操作。只要没有 writer读取锁可以由多个 reader 线程同时保持。写入锁是独占的。

你可能感兴趣的:(java clock)