Java Reference
In-Depth Information
31
// An inner class for Account
32
public static class Account {
33
private static Lock lock = new ReentrantLock(); // Create a lock
create a lock
34
private int balance = 0 ;
35
36
public int getBalance() {
37
return balance;
38 }
39
40
public void deposit( int amount) {
41
lock.lock(); // Acquire the lock
acquire the lock
42
43
try {
44
int newBalance = balance + amount;
45
46 // This delay is deliberately added to magnify the
47 // data-corruption problem and make it easy to see.
48 Thread.sleep( 5 );
49
50 balance = newBalance;
51 }
52 catch (InterruptedException ex) {
53 }
54
finally {
55
lock.unlock(); // Release the lock
release the lock
56 }
57 }
58 }
59 }
Line 33 creates a lock, line 41 acquires the lock, and line 55 releases the lock.
Tip
It is a good practice to always immediately follow a call to lock() with a try-catch
block and release the lock in the finally clause, as shown in lines 41-56, to ensure
that the lock is always released.
Listing 30.5 can be implemented using a synchronize method for deposit rather than
using a lock. In general, using synchronized methods or statements is simpler than using
explicit locks for mutual exclusion. However, using explicit locks is more intuitive and flex-
ible to synchronize threads with conditions, as you will see in the next section.
30.18
How do you create a lock object? How do you acquire a lock and release a lock?
Check
Point
30.9 Cooperation among Threads
Conditions on locks can be used to coordinate thread interactions.
Key
Point
Thread synchronization suffices to avoid race conditions by ensuring the mutual exclusion
of multiple threads in the critical region, but sometimes you also need a way for threads to
cooperate. Conditions can be used to facilitate communications among threads. A thread can
specify what to do under a certain condition. Conditions are objects created by invoking the
newCondition() method on a Lock object. Once a condition is created, you can use its
await() , signal() , and signalAll() methods for thread communications, as shown in
Figure 30.14. The await() method causes the current thread to wait until the condition is
signaled. The signal() method wakes up one waiting thread, and the signalAll() method
wakes all waiting threads.
condition
 
 
 
Search WWH ::




Custom Search