Reputation: 55
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
Upvotes: 0
Views: 82
Reputation: 4365
Why doesn't? Serialization is established on modifying and reading the value, which means that any two threads are not able to appear inside getCount
or setCount
methods of the single Runner
instance, but it doesn't make ANY guarantees on the order of execution, because it is all about scheduling. Here, ThreadThree
can just start his execution first and set the value to 3
and print it after that, which will be followed by setting the value to 2
by ThreadTwo
and printing it.
Upvotes: 1