Java Reference
In-Depth Information
Another thread got
CPU
time to print from 1 to 26 before it was preempted. The second time, the first thread (the thread
that started printing integers first) got the
CPU
time and it printed only two integers, 6 and 7, and so on. You can see
that both threads got
CPU
time. However, the amount of
CPU
time and the sequence in which they got the
CPU
time are
unpredictable. Each time you run this program, you may get a different output. The only guarantee that you get from
this program is that all integers between 1 and 500 will be printed twice in some order.
Issues in Using Multiple Threads
Some issues are involved when you use multiple threads in a program. You need to consider these issues only if
multiple threads have to coordinate based on some conditions or some shared resources.
In the previous sections, the examples involving threads were trivial. They simply printed some integers on the
standard output. Let's have a different kind of example that uses multiple threads, which access and modify the value
of a variable. Listing 6-4 has the code for a
BalanceUpdate
class. Note that all methods defined in the
BalanceUpdate
class are
static
.
Listing 6-4.
Multiple Threads Modifying the Same Variable
// BalanceUpdate.java
package com.jdojo.threads;
public class BalanceUpdate {
// 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 void updateBalance() {
// Add 10 to balance and subtract 10 from balance
balance = balance + 10;
balance = balance - 10;
}
public static 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();
}