I am trying to grasp the concept of synchronized methods in Java, but encountered the behavior that seems confusing, at least to me; In the code:
public class parallelUpdate
{
public static void main(String[] args)
{
Ob ob = new Ob();
new Thread(ob).start();
new Thread(ob).start();
}
}
class Ob implements Runnable
{
static int cnt = 0;
private synchronized void inc()
{
cnt++;
}
@Override
public void run()
{
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread());
inc();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
... incrementing is performed in parallel by both treads:
Thread[Thread-0,5,main]
Thread[Thread-1,5,main]
Thread[Thread-0,5,main]
Thread[Thread-1,5,main]
Thread[Thread-1,5,main]
Thread[Thread-0,5,main]
Thread[Thread-0,5,main]
Thread[Thread-1,5,main]
I expected that the use of synchronized for the inc() method would yield sequential incrementing, like:
Thread[Thread-0,5,main]
Thread[Thread-0,5,main]
Thread[Thread-0,5,main]
Thread[Thread-0,5,main]
Thread[Thread-0,5,main]
Thread[Thread-1,5,main]
Thread[Thread-1,5,main]
Thread[Thread-1,5,main]
Thread[Thread-1,5,main]
Thread[Thread-1,5,main]
What is wrong with my code?