|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Another way to ensure exclusive access to a section of code is to use an explicit lock. An explicit lock is more flexible than using thesynchronizedkeyword because the lock can span a few statements in a method, or multiple methods in addition to the scopes (block and method) supported bysynchronized.To create an explicit lock you instantiate an implementation of the
Lockinterface, usuallyReentrantLock. To grab the lock, you invoke thelockmethod; to release the lock you invoke theunlockmethod. Since the lock is not automatically released when the method exits, you should wrap thelockandunlockmethods in atry/finallyclause.To wait on an explicit lock, you create a condition variable (an object that supports the
Conditioninterface) using theLock.newConditionmethod. Condition variables provide the methodsawaitto wait for the condition to be true, andsignalandsignalAllto notify all waiting threads that the condition has occurred. Like theObject.waitmethod,Condition.awaithas several variants, which are listed in the next table.In the following example,
Condition.awaitMethodsMethod Description awaitWaits for a condition to occur. awaitInterruptiblyWaits for a condition to occur. Cannot be interrupted. awaitNanos(long timeout)Waits for a condition to occur. If the notification does not occur before a timeout specified in nanoseconds, it returns. await(long timeout, TimeUnit unit)Waits for a condition to occur. If the notification does not occur before a timeout specified in the provided time unit, it returns. await(Date timeout)Waits for a condition to occur. If the notification does not occur before the specified time, it returns. CubbyHolehas been rewritten to use an explicit lock and condition variable. To run this version of the Producer-Consumer example, executeProducerConsumerTest2.import java.util.concurrent.locks.*; public class CubbyHole2 { private int contents; private boolean available = false; private Lock aLock = new ReentrantLock(); private Condition condVar = aLock.newCondition(); public int get(int who) { aLock.lock(); try { while (available == false) { try { condVar.await(); } catch (InterruptedException e) { } } available = false; System.out.println("Consumer " + who + " got: " + contents); condVar.signalAll(); } finally { aLock.unlock(); return contents; } } public void put(int who, int value) { aLock.lock(); try { while (available == true) { try { condVar.await(); } catch (InterruptedException e) { } } contents = value; available = true; System.out.println("Producer " + who + " put: " + contents); condVar.signalAll(); } finally { aLock.unlock(); } } }
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.