I have started learning about multi-threading and synchronization in Java and decided to do some practical. I wrote a simple code wherein I have two synchronized methods whose class object is being shared by three threads, but when I run this code , synchronization doesn't seem to work, am I missing a point here? Any help is greatly appreciated.
Runner.java
public class Runner {
private int count;
public synchronized int getCount() {
return count;
}
public synchronized void setCount(int count) {
this.count = count;
}
}
ThreadOne.java
public class ThreadOne extends Thread{
Runner r;
int count;
public ThreadOne(Runner r , int count)
{
this.r=r;
this.count=count;
}
@Override
public void run()
{
r.setCount(count);
System.out.println("count is: "+r.getCount());
}
}
Similarly, I have ThreadTwo.java and ThreadThree.java classes and finally the main class:
MainRunner.java
public class MainRunner {
public static void main(String[] args) {
// TODO Auto-generated method stub
Runner runner = new Runner();
ThreadOne one = new ThreadOne(runner, 1);
ThreadTwo two = new ThreadTwo(runner, 2);
ThreadThree three = new ThreadThree(runner, 3);
one.start();
two.start();
three.start();
}
}
And the Output I am getting is:
count is: 1
count is: 3
count is: 2
It doesn't look synchronized. I know I am missing something here, Please let me know. Thanks in advance