Java Reference
In-Depth Information
59 System.out.println( "\t\t\tWait for a deposit" );
60
newDeposit.await();
wait on the condition
61 }
62
63 balance -= amount;
64 System.out.println( "\t\t\tWithdraw " + amount +
65
"\t\t" + getBalance());
66 }
67 catch (InterruptedException ex) {
68 ex.printStackTrace();
69 }
70
finally {
71
lock.unlock(); // Release the lock
release the lock
72 }
73 }
74
75 public void deposit( int amount) {
76 lock.lock(); // Acquire the lock
77 try {
78 balance += amount;
79 System.out.println( "Deposit " + amount +
80
acquire the lock
"\t\t\t\t\t" + getBalance());
81
82
// Signal thread waiting on the condition
83
newDeposit.signalAll();
signal threads
84 }
85
finally {
86
lock.unlock(); // Release the lock
release the lock
87 }
88 }
89 }
90 }
The example creates a new inner class named Account to model the account with two meth-
ods, deposit(int) and withdraw(int) , a class named DepositTask to add an amount
to the balance, a class named WithdrawTask to withdraw an amount from the balance, and a
main class that creates and launches two threads.
The program creates and submits the deposit task (line 10) and the withdraw task (line 11).
The deposit task is purposely put to sleep (line 23) to let the withdraw task run. When there are
not enough funds to withdraw, the withdraw task waits (line 59) for notification of the balance
change from the deposit task (line 83).
A lock is created in line 44. A condition named newDeposit on the lock is created in
line 47. A condition is bound to a lock. Before waiting or signaling the condition, a thread
must first acquire the lock for the condition. The withdraw task acquires the lock in line
56, waits for the newDeposit condition (line 60) when there is not a sufficient amount
to withdraw, and releases the lock in line 71. The deposit task acquires the lock in line 76
and signals all waiting threads (line 83) for the newDeposit condition after a new deposit
is made.
What will happen if you replace the while loop in lines 58-61 with the following if
statement?
if (balance < amount) {
System.out.println( "\t\t\tWait for a deposit" );
newDeposit.await();
}
The deposit task will notify the withdraw task whenever the balance changes.
(balance < amount) may still be true when the withdraw task is awakened. Using the if
 
Search WWH ::




Custom Search