java - synchronized block is not working quite right -


i unable synchronized blocks in java

i read following post didn't quite syn-blocks , locks

synchronized block not working

i don't know why below code not outputting uniform array of a's,b's,c's after synchronized it..

    public class synchronizeblock {     static stringbuffer s=new stringbuffer();     public static void main(string []args)     {         threading t1=new threading(s,'a');         threading t2=new threading(s,'b');         threading t3=new threading(s,'c');         t1.start();         t2.start();         t3.start();          } } class threading extends thread {     stringbuffer sb;      char ch;      threading()     {      }     threading(stringbuffer sb,char ch)     {         this.sb=sb;         this.ch=ch;     }     public void run()     {         synchronized(this)   // this(current instance) acts lock ??         {                 for(int i=0;i<20;++i)                 {                     system.out.print(ch);                 }         }            }  } 

one of cases of output below:

bbbbbbbbbbbbbaccccccccccccccccccccaaaaaaaaaaaaaaaaaaabbbbbbb

my concern once thread started ,say thread character 'b' (be thread-"one")shouldn't completed before thread gets chance run because thread "one" got lock on object,correct me if wrong , have following questions

  1. it's confusing "what gets locked" , "what acts lock". explain got locked in code

  2. and should uniform output (by saying uniform output here ,i mean once thread starts character should printed 20 times)

first of stringbuffer are

string buffers safe use multiple threads. methods synchronized necessary operations on particular instance behave if occur in serial order consistent order of method calls made each of individual threads involved.

and rest can read in bottom of question problem not print output a's b's c's threads run if current thread not finish can use join() method tell's other thread wait until job finish go job so, main methods this

      threading t1 = new threading(s,'a');       threading t2 = new threading(s,'b');       threading t3 = new threading(s,'c');       t1.start();       t1.join();       t2.start();       t2.join();       t3.start(); 

Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -