user4206193
user4206193

Reputation:

Synchronizing 10 threads in Java

Why do I get

22291 3091 0 351 0 1423 0 0 0 0

and not

0 0 0 0 0 0 0 0 0 0

when I run this code in Java:

import java.lang.Thread;

class MainThread {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) new MyThread().start();
    }
}

class MyThread extends Thread {
    static int counter = 0;
    static Object mutex = new Object();
    public void run() {
        synchronized (mutex) {
            for (int i = 0; i < 1000000; i++) counter = counter + 1;
            for (int i = 0; i < 1000000; i++) counter = counter - 1;
        }
        System.out.print(counter + " ");
    }
}

Upvotes: 0

Views: 54

Answers (1)

Salih Erikci
Salih Erikci

Reputation: 5087

You get that output because print statement is not syncronized. After a thread finishes two for loop and exists from the syncronized block, the counter = 0.
But before it prints out the counter some other thread get into the syncronized block and starts incrementing the counter.
That's why the previous thread prints the incremented counter.

public void run() {
    synchronized (mutex) {
        for (int i = 0; i < 1000000; i++) counter = counter + 1;
        for (int i = 0; i < 1000000; i++) counter = counter - 1;
    }
    // Here the current thread exited the sync block and some other thread get into this block  
    // and started incrementing the counter

    System.out.print(counter + " "); // your thread prints incremented counter
}

Upvotes: 2

Related Questions