ReentrantLockノート(一)--基本使用

8567 ワード

ReentrantLock基本使用


こうごしゅつりょく
ReentrantLock lock = new ReentrantLock(true);//true ,false 
Runnable r = () -> {
    while (!Thread.currentThread().isInterrupted()) {
        lock.lock();
        try {
            System.out.println(" :" + Thread.currentThread().getName());
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            lock.unlock();
        }
    }
};
new Thread(r).start();
Thread.sleep(10);
new Thread(r).start();
Thread.sleep(10);
new Thread(r).start();

生産者、消費者
ReentrantLock lock = new ReentrantLock();
LinkedList queue = new LinkedList();
Condition notEmpty = lock.newCondition();
Condition notFull = lock.newCondition();
int max = 5;
new Thread(() -> {
    while (!Thread.currentThread().isInterrupted()) {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                try {
                    System.out.println(" ...");
                    notEmpty.await();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            queue.poll();
            System.out.println(" , :" + queue.size());
            notFull.signalAll();
        } finally {
            lock.unlock();
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}).start();

new Thread(() -> {
    while (!Thread.currentThread().isInterrupted()) {
        lock.lock();
        try {
            while (queue.size() >= max) {
                try {
                    System.out.println(" ...");
                    notFull.await();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            queue.add(1);
            System.out.println(" , :" + queue.size());
            notEmpty.signalAll();
        } finally {
            lock.unlock();
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}).start();

カスタムロック
    class Mutex implements Lock, java.io.Serializable {
       //  , 
       private static class Sync extends AbstractQueuedSynchronizer {
         //  
         protected boolean isHeldExclusively() {
           return getState() == 1;
         }
         //  0 
         public boolean tryAcquire(int acquires) {
           assert acquires == 1; // Otherwise unused
           if (compareAndSetState(0, 1)) {
             setExclusiveOwnerThread(Thread.currentThread());
             return true;
           }
           return false;
         }
         //  , 0
         protected boolean tryRelease(int releases) {
           assert releases == 1; // Otherwise unused
           if (getState() == 0) throw new IllegalMonitorStateException();
           setExclusiveOwnerThread(null);
           setState(0);
           return true;
         }
         //  Condition, condition condition 
         Condition newCondition() { return new ConditionObject(); }
       }
       //  Sync 
       private final Sync sync = new Sync();
       public void lock()                { sync.acquire(1); }
       public boolean tryLock()          { return sync.tryAcquire(1); }
       public void unlock()              { sync.release(1); }
       public Condition newCondition()   { return sync.newCondition(); }
       public boolean isLocked()         { return sync.isHeldExclusively(); }
       public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); }
       public void lockInterruptibly() throws InterruptedException {
         sync.acquireInterruptibly(1);
       }
       public boolean tryLock(long timeout, TimeUnit unit)
           throws InterruptedException {
         return sync.tryAcquireNanos(1, unit.toNanos(timeout));
       }
     }