I’m currently learning about multithreading in Java and encountered an interesting behavior that I’m struggling to understand. I have a simple Java program that utilizes multithreading to increment a counter, but I’m getting inconsistent output based on the placement of print statements in the code.
class Counter{
int count=1;
public void increment(){
count++;
}
}
public class test {
public static void main(String[] args) {
Counter counter1= new Counter();
Runnable obj1 = ()->{
for(int i=0; i<1000;i++)
{
counter1.increment();
//System.out.println("obj1 : "+ counter1.count);
}
};
Runnable obj2 = ()->{
for(int i=0; i<1000;i++)
{
counter1.increment();
// System.out.println("obj2 : "+counter1.count);
}
};
// System.out.println(counter1.count);
Thread t1 = new Thread(obj1);
// System.out.println(counter1.count);
Thread t2 = new Thread(obj2);
// System.out.println(counter1.count);
t1.start();
// System.out.println(counter1.count);
t2.start();
System.out.println("result is :" + counter1.count);
}}
When I comment out all the System.out.println(counter1.count); statements except the last one, I consistently get 1 as the output. However, when I keep all the print statements, I get varying output like 577, which seems to be the result of both threads’ increments.
Could someone please help me understand why this inconsistency occurs? I’m particularly interested in why commenting out the print statements affects the final output of the program.
Any insights or explanations would be greatly appreciated. Thank you!
Amir Abram is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.