Java Reference
In-Depth Information
I will answer one more question before you can see this big discussion about thread synchronization in action.
The question is, “Which thread gets a chance to acquire the object's monitor lock when there are some blocked
threads in the entry set and some woken up threads in the wait set?” Note that the threads that are in the wait set do
not compete for the object's monitor until they are woken up by the notify() or notifyAll() call. The answer to this
question is that it depends on the scheduler's algorithm of the operating system.
Listing 6-5 has the code for the BalanceUpdateSynchronized class, which is a modified version of the
BalanceUpdate class listed in Listing 6-4. The only difference between the two classes is the use of the keyword
synchronized to declare the updateBalance() and monitorBalance() methods in the new class, so only one
thread can enter one of the methods at a time. When you run the new class, you will not see any output because the
monitorBalance() method will never see the value of the balance variable other than 100.
Listing 6-5. Synchronized Balance Update
// BalanceUpdateSynchronized.java
package com.jdojo.threads;
public class BalanceUpdateSynchronized {
// Initialize balance to 100
private static int balance = 100;
public static void main(String[] args) {
startBalanceUpdateThread(); // Thread to update the balance value
startBalanceMonitorThread(); // Thread to monitor the balance value
}
public static synchronized void updateBalance() {
// Add 10 to balance and subtract 10 from balance
balance = balance + 10;
balance = balance - 10;
}
public static synchronized void monitorBalance() {
int b = balance;
if (b != 100) {
System.out.println("Balance changed: " + b);
System.exit(1); // Exit the program
}
}
public static void startBalanceUpdateThread() {
// Start a new thread that calls the updateBalance() method in an infinite loop
Thread t = new Thread(() -> {
while (true) {
updateBalance();
}
});
t.start();
}
Search WWH ::




Custom Search