Friday, 15 August 2014

multithreading - Synchronizing 10 threads in Java -



multithreading - Synchronizing 10 threads in Java -

why get

22291 3091 0 351 0 1423 0 0 0 0

and not

0 0 0 0 0 0 0 0 0 0

when run code in java:

import java.lang.thread; class mainthread { public static void main(string[] args) { (int = 0; < 10; i++) new mythread().start(); } } class mythread extends thread { static int counter = 0; static object mutex = new object(); public void run() { synchronized (mutex) { (int = 0; < 1000000; i++) counter = counter + 1; (int = 0; < 1000000; i++) counter = counter - 1; } system.out.print(counter + " "); } }

you output because print statement not syncronized. after thread finishes 2 loop , exists syncronized block, counter = 0. before prints out counter other thread syncronized block , starts incrementing counter. that's why previous thread prints incremented counter.

public void run() { synchronized (mutex) { (int = 0; < 1000000; i++) counter = counter + 1; (int = 0; < 1000000; i++) counter = counter - 1; } // here current thread exited sync block , other thread block // , started incrementing counter system.out.print(counter + " "); // thread prints incremented counter }

java multithreading

No comments:

Post a Comment