look at these code, why so frustrating?# Java - 爪哇娇娃
s*s
1 楼
public void withdraw(int amount) {
56 lock.lock();// Acquire the lock
57 try {
58 while (balance < amount) {
59 System.out.println("\t\t\tWait for a deposit")
60 newDeposit.await();
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 // Release the lock
72 }
73 }
书上说:
What will happen if you replace the while loop in lines 59–60 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 statement, the withdraw task may wait forever.
我觉得无法理解为什么, while loop 变成 if 之后, withdraw就要wait forever???
56 lock.lock();// Acquire the lock
57 try {
58 while (balance < amount) {
59 System.out.println("\t\t\tWait for a deposit")
60 newDeposit.await();
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 // Release the lock
72 }
73 }
书上说:
What will happen if you replace the while loop in lines 59–60 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 statement, the withdraw task may wait forever.
我觉得无法理解为什么, while loop 变成 if 之后, withdraw就要wait forever???