As per my understanding if i have used a synchronized keyword then only one thread can enter and once it leaves then only other thread.But why my below code is printing sometimes First 2 Second 2
package com.vikash.GeeksForGeeks;
public class Test implements Runnable{
private static int count;
public synchronized void incrementCount()
{
count++;
System.out.println(Thread.currentThread().getName()+" "+count);
}
public static void main(String[] args) throws InterruptedException {
Thread t1=new Thread(new Test());
Thread t2=new Thread(new Test());
t1.start();t1.setName("First");
t2.start();t2.setName("Second");
t1.join();
t2.join();
System.out.println("Count Value="+count);
}
@Override
public void run() {
incrementCount();
}
}
You're creating two separate instances of Test
, and your incrementCount
method is an instance method despite it incrementing a static variable.
Each of your threads operates on a different instance of Test
, so they won't block each other, and you run into the normal race conditions.
If you make incrementCount
a static method, then both threads will be trying to acquire the monitor for Test.class
, and it should work in those terms. (Although there's no guarantee that the main
thread will read the most-recently-written value of count
...)
Alternatively, create one instance of Test
, and pass that to both Thread
constructors, at which point they'll both be trying to acquire the monitor for the same instance of Test
. The crucial point is that if the two threads are acquiring different monitors, they'll both be able to do it without waiting for the other...
See more on this question at Stackoverflow