10 Replies Latest reply: Mar 8, 2013 5:22 AM by Kayaman RSS

    StringBuffer when used with multi thread show output in UnSynchronize way.

      below is my code :-

      public class Two implements Runnable
           //thread safe
      static StringBuffer builder=new StringBuffer("output:1");
      Two(StringBuffer builder)
           public void run()
                System.out.println("Printed by "+Thread.currentThread().getName()+" : "+builder.append(" output:5"));
      public static void main(String s[])
           builder.append(" output:2");
           Two d1=new Two(builder);
           Thread t1=new Thread(d1);
           Thread t2=new Thread(d1);
           Thread t3=new Thread(d1);
           builder.append(" output:3");
           builder.append(" output:4");
           System.out.println("Printed by "+Thread.currentThread().getName()+" : "+builder);

      when the program is executed it show different output in corresponds to the order of call and it is not showing thread saftey.