java - What is the difference between Thread.join and Synchronised? -
i confused when use thread.join()
, when use synchronization
in multi threading application.
according me, both of them block or wait execution done other thread.
example has output 10 a's , 10 b's & 10 c's in sequential pattern 1 after other :
1 : 2 : 3 : 4 : 5 : 6 : 7 : 8 : 9 : 10 : 1 : b 2 : b 3 : b 4 : b 5 : b 6 : b 7 : b 8 : b 9 : b 10 : b 1 : c 2 : c 3 : c 4 : c 5 : c 6 : c 7 : c 8 : c 9 : c 10 : c ----program ends----
example starts here
class synctest extends thread { stringbuffer sb; public synctest(stringbuffer sb) { this.sb = sb; } public void run() { synchronized(sb) { for(int i=1;i<=10;i++){ system.out.println(i+" : "+sb.charat(0)); } sb.setcharat(0, (char) (sb.charat(0)+1)); } } public static void main(string [] args) throws interruptedexception { stringbuffer sb = new stringbuffer("a"); thread t1=new synctest(sb); thread t2=new synctest(sb); thread t3=new synctest(sb); t1.start(); t2.start(); t3.start(); thread.sleep(1000); system.out.println("----program ends----"); } }
here, output turns out 10 a's followed 10 b's followed 10 c's in sequential order. can use thread.join
instead of synchronized
block same output this:
public void run() { //removed synchronized statement... for(int i=1;i<=10;i++){ system.out.println(i+" : "+sb.charat(0)); } sb.setcharat(0, (char) (sb.charat(0)+1)); } public static void main(string [] args) throws interruptedexception { stringbuffer sb = new stringbuffer("a"); thread t1=new synctest(sb); thread t2=new synctest(sb); thread t3=new synctest(sb); t1.start(); t1.join(); t2.start(); // wait t1 complete t2.join(); t3.start(); // wait t2 complete t3.join(); // wait t3 complete system.out.println("----program ends----"); }
can clear confusion on usage of these 2 techniques i.e. when use thread.join
, when use synchronization
in multi-threading on java.
thread.join()
waits thread finish, whereas synchronized
block can used prevent 2 threads executing same piece of code @ same time.
it's hard advise when use 1 on other in general, since serve different purposes. it's rare find example, such code, difference between 2 minimal.
that being said, in first example there no guarantee output alphabetical. can't sure thread synchronized
block first. in particular case, join()
appropriate.
Comments
Post a Comment