I have following codes:
public class MyApp {
public static void main(String[] args) throws InterruptedException {
SharedResource sharedResource = new SharedResource();
Runnable first = () -> {
sharedResource.increment(10000);
};
Runnable second = () -> {
sharedResource.increment(10000);
};
Thread thread = new Thread(first, "FirstThread");
Thread thread2 = new Thread(second, "SecondThread");
thread.start();
thread2.start();
thread.join();
thread2.join();
System.out.println("The value of counter is " + sharedResource.getCounter());
}
}
Using this class:
public class SharedResource {
private int counter;
public void increment(int times) {
for (int x=1; x<=times;x++) {
counter++;
// System.out.println(counter);
}
}
public void decrement() {
counter--;
}
public int getCounter() {
return counter;
}
}
I am curious why this happens all the time.
When System.out.println()
is removed from the increment method, the total value of
System.out.println("The value of counter is " + sharedResource.getCounter());
is random - which is excepted because multiple threads are sharing the same counter
.
However, when System.out.println(counter);
is presented on the increment method, the code no longer seems to have the multi-threading issue.
The final result of counter is always 20,000 which is excepted as the code is lopping 10,000 times from each thread. Can anybody explain me why is this happening?