java - Varying outputs with a synchronized method -
i have written multi-threaded , synchronized incrementing function doesn't show consistent output :-
$ java main count: 999883 $ java main count: 1000000 $ java main count: 999826 $ java main count: 1000000 $ java main count: 1000000
i have synchronized counter :-
public class counter { public int count; synchronized void inc() { count = count+1; } int getcount() { homecoming count; } }
a thread class initialized counter object , increments 1000 times :-
public class countprimesrunnable implements runnable { private counter c; public countprimesrunnable(counter c) { this.c = c; } public void run() { (int = 0; < 1000; i++) c.inc(); } }
and main class creates 1000 threads @ time :-
public class main { public static void main(string[] args) { int numberofthreads = 1000; thread[] worker = new thread[numberofthreads]; counter c = new counter(); (int = 0; < numberofthreads; i++) worker[i] = new thread(new countprimesrunnable(c)); (int = 0; < numberofthreads; i++) worker[i].start(); system.out.println("count: " + c.count); } }
what missing ?
but doesn't show consistent output :-
that's because, it's not sure code main
thread finish after other threads done job. in cases result less 1000000
, cases, threads still execute after main thread has finished.
you can invoke thread#join()
method on each of newly created thread create sure main
method waits threads die, before continuing execution after loop.
so, have add together loop invoke join
on each of threads started, , can avoid using 2nd loop, merging first one:
for (int = 0; < numberofthreads; i++) { worker[i] = new thread(new countprimesrunnable(c)); worker[i].start(); } (int = 0; < numberofthreads; i++) { worker[i].join(); }
when invoke join
on thread a
within thread b
, thread b
go on farther execution after thread a
dies.
java multithreading
No comments:
Post a Comment