Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

thread synchronization  RSS feed

 
anoop reddy
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

In the below sample code iam obtaining the lock on stringbuffer object k and trying to print string value for 10 times,when first thread enters to sync block iam trying to print "A" 10 times and sleeping this thread for sometime before i output eachtime, when this thread sleeps, second thread obtains lock and prints "B", Now my question is how can second thread enter synchronized block, when my first thread has already obtained a lock.

public class SampleSync {
public static void main(String args[]) {
StringBuffer s = new StringBuffer("A");
MyThread one = new MyThread(s);
s = new StringBuffer("B");
MyThread two = new MyThread(s);
s = new StringBuffer("C");
MyThread three = new MyThread(s);
one.start();
two.start();
three.start();
}
}
class MyThread extends Thread {
StringBuffer k;
MyThread(StringBuffer sb) {
k = sb;
}
public void run() {
synchronized(k) {
for(int i = 0;i<10;i++) {
System.out.println(k);
try {
Thread.sleep(1000);
}catch(InterruptedException ie){
}
}
}
}
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 15861
81
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, you are passing each thread a new, different StringBuffer object. So the first thread indeed gets the lock on the StringBuffer that contains "A", but the second thread is looking at an entirely different StringBuffer (the one that contains "B"), and the third thread is looking at yet another StringBuffer (that contains "C").

You see, the second and third threads are not at all trying to lock the same StringBuffer object as the first thread - they have their own, separate StringBuffer objects that they're locking.
 
Ajay Saxena
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You see, the second and third threads are not at all trying to lock the same StringBuffer object as the first thread - they have their own, separate StringBuffer objects that they're locking.

In fact syncronization is done on something that needs to be concurrently accessible. So if we have multiple threads access a single object of some class with a possible state (some state variables),we might consider going for sync. Because we may have these threads invoke methods on the object that change the state of the latter(doing some manipulations that are non-atomic)

So,in your case, the code is not expected to do what you have set out to achieve. (Think !!)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!