java - Different Output with Join method -
i read tutorials , asked question here
but confused again join method. know java cannot guarantee order of execution of threads under normal circumstances.
what read using join() ,it makes sure thread calls join,the current thread not execute unless thread have called join finished.
my example tried
public class threadtest1 extends thread{ @override public void run() { super.run(); for(int i=0; i<10; i++) { system.out.println(i + " :"+ thread.currentthread().getname()); } } public static void main(string[] args) { system.out.println("thread getting started"); threadtest1 th0= new threadtest1(); th0.start(); threadtest1 th1= new threadtest1(); th1.start(); try { th1.join(10000); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } } }
outputs:
first time output 0 :thread-1 1 :thread-1 2 :thread-1 0 :thread-0 3 :thread-1 1 :thread-0 4 :thread-1 2 :thread-0 5 :thread-1 3 :thread-0 6 :thread-1 4 :thread-0 7 :thread-1 8 :thread-1 9 :thread-1 5 :thread-0 6 :thread-0 7 :thread-0 8 :thread-0 9 :thread-0
second time output: 0 :thread-1 0 :thread-0 1 :thread-1 1 :thread-0 2 :thread-1 2 :thread-0 3 :thread-1 3 :thread-0 4 :thread-1 4 :thread-0 5 :thread-1 5 :thread-0 6 :thread-1 6 :thread-0 7 :thread-1 7 :thread-0 8 :thread-1 8 :thread-0 9 :thread-1 9 :thread-0
why both outputs different.
i used join() th1 object. when th0 running , jvm found th1 thread thread-1 should finished first thread-0.
why printing thread-1, thread-0 without sequence. if outputs use of join() methd?
can please explain outputs.
the problem here both threads start independently , start printing stuff, happens between th0.start
, th1.start
not deterministic.
also, it main system thread of application waiting th1
complete, th0
, th1
execute run
method independently each other, that's why every time differente sequence.
Comments
Post a Comment