i am unable to get synchronized blocks in java
i read this following post but didn't quite get about syn-blocks and locks
Synchronized block not working
i don't know why below code is not outputting uniform array of A's,B's,C's even after i 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 as lock ??
{
for(int i=0;i<20;++i)
{
System.out.print(ch);
}
}
}
}
one of cases of output is as below:
bbbbbbbbbbbbbaccccccccccccccccccccaaaaaaaaaaaaaaaaaaabbbbbbb
my concern is that once a thread is started ,say thread with character 'b' (be it thread-"one")shouldn't it be completed before another thread gets chance to run because thread "one" got lock on the object,correct me if am wrong and i have following questions
it's really confusing "what gets locked" and "what acts as lock". So explain what exactly got locked in my code
and what should i do to get uniform output (by saying uniform output here ,i mean that once a thread starts its character should get printed 20 times)