Java multithreading is not thread safe using synchronized

Simple multi-threaded test with synchronization. I thought that if it is "synchronized", other threads will wait. What am I missing?

public class MultithreadingCounter implements Runnable { static int count = 0; public static void main(String[] args) { int numThreads = 4; Thread[] threads = new Thread[numThreads]; for (int i = 0; i < numThreads; i++) threads[i] = new Thread(new MultithreadingCounter(), i + ""); for (int i = 0; i < numThreads; i++) threads[i].start(); for (int i = 0; i < numThreads; i++) try { threads[i].join(); } catch (Exception e) { e.printStackTrace(); } } @Override public void run() { increment(); } public synchronized void increment(){ System.out.print(Thread.currentThread().getName() + ": " + count + "\t"); count++; // if I put this first or increment it directly in the print line, it works fine. } } 

I thought it would look something like this:

 0: 1 2: 0 1: 2 3: 3 

But its actual conclusion:

 0: 0 2: 0 1: 0 3: 3 

and other options like this. It should display every increment (i.e. 0,1,2,3) out of order ...

+4
source share
3 answers

The synchronized is in the instance method. None of the two threads can execute this method of one of your thread objects at the same time. But that is not what your code does. Each thread executes this method on its own instance. Syncing does not do what you seem to be going to. If it were a static method, that would be.

+7
source

Your increment method should be static :

 public static synchronized void increment() { 

Right now, every object is synchronized in this separate instance, but since count is a static variable, you must synchronize yourself directly with the Class object.

+1
source

when a synchronized keyword is used before a method, it ensures that this method can only be executed on one thread at a time, only with respect to this object. It does not provide thread safety from other objects.

0
source

All Articles