synchronization of methods(Topic-Threads)

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
pre

synchronization of methods(Topic-Threads)

Post by pre »

class Pt extends Thread
{
StringBuffer j = new StringBuffer();
public synchronized void run()
{

for(int i =0;i<2;i++)
System.out.println(j);
j.append("b");

}
Pt(StringBuffer j)
{
this.j=j;
}
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("a") ;
Pt t1 = new Pt(s);
Pt t2 = new Pt(s);
Pt t3 = new Pt(s);
t1.start();
t2.start();
t3.start();
}
}
what is wrong with this code? why isn't it behaving the same. I mean it should always produce 2"a"s , 2"ab"s and 2"abb"s. But it isn't behaving the same.
help me

admin
Site Admin
Posts: 10066
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: synchronization of methods(Topic-Threads)

Post by admin »

You are creating three Pt objects and starting each of them. So there are three threads but each thread is working on its own Pt object. synchronized works if multiple threads work on the same object.

It is like you have three people trying to enter three different rooms. Even if one person locks his room, it won't affect others because the other two are trying to enter different rooms. For synchronization to work, you need to have just one room. When one person locks this room, other people cannot enter until the first person releases the lock.

HTH,
Paul.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 242 guests