This discussion is archived
10 Replies Latest reply: Mar 8, 2013 3:22 AM by Kayaman RSS

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

995438 Newbie
Currently Being Moderated
below is my code :-

public class Two implements Runnable
{
     
     //thread safe
static StringBuffer builder=new StringBuffer("output:1");
     
     
Two(StringBuffer builder)
     {
          this.builder=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);
     
     t1.start();
     t2.start();
     t3.start();
     
     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.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points