10 Replies Latest reply on Mar 8, 2013 11:22 AM by Kayaman

    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.