Java Reference
In-Depth Information
public static void startBalanceMonitorThread() {
// Start a thread that monitors the balance value
Thread t = new Thread(() -> {
while (true) {
monitorBalance();
}
});
t.start();
}
}
Balance changed: 110
A brief description of each component of this class is as follows:
balance
: It is a
static
variable of type
int
. It is initialized to
100
.
•
updateBalance()
: It is a
static
method that adds
10
to the
static
variable
balance
and
subtracts
10
from it. Upon completion of this method, the value of the
static
variable
balance
is expected to remain the same as 100.
•
startBalanceUpdateThread()
: It starts a new thread that keeps calling the
updateBalance()
method in an infinite loop. That is, once you call this method, a thread keeps adding
10
to the
balance
variable and subtracting
10
from it.
•
startBalanceMonitorThread()
: It starts a new thread that monitors the value of the
balance
static
variable. When the thread detects that the value of the
balance
variable is other than
100
, it prints the current value and exits the program.
•
main()
: This method is used to run the program. It starts a thread that updates the
balance
class variable in a loop using the
updateBalance()
method. It also starts another thread that
monitors the value of the
balance
class variable.
The program consists of two threads. One thread calls the
updateBalance()
method, which adds
10
to
balance
and subtracts
10
from it. That is, after this method finishes executing, the value of the
balance
variable is expected to
remain unchanged. Another thread monitors the value of the
balance
variable. When it detects that the value of the
balance
variable is anything other than
100
, it prints the new value and exits the program.
Intuitively, the balance monitor thread should not print anything because the
balance
should always be
100
and
the program should never end because both threads are using infinite loops. However, that is not the case. If you run
this program, you will find, in a short time, the program prints the
balance
value other than
100
and exits.
Suppose on a particular machine the statement
"balance = balance + 10;"
is implemented as the following
machine instructions assuming
register-1
as a CPU register:
•
register-1 = balance;
register-1 = register-1 + 10;
balance = register-1;
Similarly, assume that the statement
"balance = balance - 10;"
is implemented as the following machine
instructions assuming
register-2
as another CPU register:
register-2 = balance;
register-2 = register-2 - 10;
balance = register-2;