Java Reference
In-Depth Information
servedword)istheirabilitytobackoutofanattempttoacquirealock.Forexample,
the
tryLock()
methodbacksoutwhenthelockisnotavailableimmediatelyorwhen
a timeout expires (if specified). Also, the
lockInterruptibly()
method backs
out when another thread sends an interrupt before the lock is acquired.
ReentrantLock
implements
Lock
,describingareentrantmutualexclusion
Lock
implementationwiththesamebasicbehaviorandsemanticsastheimplicitmonitorlock
accessed via
synchronized
, but with extended capabilities.
thatensuresthattheoutputisnevershowninincorrectorder(aconsumedmessageap-
pearing before a produced message).
Listing 6-4.
Achieving synchronization in terms of locks
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class PC
{
public static void main(String[] args)
{
final Lock lock = new ReentrantLock();
final BlockingQueue<Character> bq;
bq = new ArrayBlockingQueue<Character>(26);
final
ExecutorService
executor
=
Execut-
ors.newFixedThreadPool(2);
Runnable producer;
producer = new Runnable()
{
public void run()
{
for (char ch = 'a'; ch <= 'z'; ch++)