img
Method
Description
void lock( )
Waits until the invoking lock can be acquired.
void lockInterruptibly( )
Waits until the invoking lock can be acquired, unless
throws InterruptedException
interrupted.
Condition newCondition( )
Returns a Condition object that is associated with the
invoking lock.
boolean tr yLock( )
Attempts to acquire the lock. This method will not wait
if the lock is unavailable. Instead, it returns true if the
lock has been acquired and false if the lock is currently
in use by another thread.
boolean tr yLock(long wait, TimeUnit tu) Attempts to acquire the lock. If the lock is unavailable,
throws InterruptedException
this method will wait no longer than the period specified
by wait, which is in tu units. It returns true if the lock has
been acquired and false if the lock cannot be acquired
within the specified period.
void unlock( )
Releases the lock.
TABLE 26-1
The Lock Methods
java.util.concurrent.locks supplies an implementation of Lock called ReentrantLock.
ReentrantLock implements a reentrant lock, which is a lock that can be repeatedly entered
by the thread that currently holds the lock. (Of course, in the case of a thread reentering a
lock, all calls to lock( ) must be offset by an equal number of calls to unlock( ).) Otherwise,
a thread seeking to acquire the lock will suspend until the lock is not in use.
The following program demonstrates the use of a lock. It creates two threads that access
a shared resource called Shared.count. Before a thread can access Shared.count, it must obtain
a lock. After obtaining the lock, Shared.count is incremented and then, before releasing the
lock, the thread sleeps. This causes the second thread to attempt to obtain the lock.
However, because the lock is still held by the first thread, the second thread must wait until
the first thread stops sleeping and releases the lock. The output shows that access to
Shared.count is, indeed, synchronized by the lock.
// A simple lock example.
import java.util.concurrent.locks.*;
class LockDemo {
public static void main(String args[]) {
ReentrantLock lock = new ReentrantLock();
new LockThread(lock, "A");
new LockThread(lock, "B");
}
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home