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
synchronization of methods(Topic-Threads)
Moderator: admin
-
- Site Admin
- Posts: 10066
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: synchronization of methods(Topic-Threads)
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.
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.
Who is online
Users browsing this forum: No registered users and 243 guests