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++;
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 ...
source share