aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Threads and sleep Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Threads and sleep" Watch "Threads and sleep" New topic
Author

Threads and sleep

Lisa Yanchunis
Greenhorn

Joined: Nov 03, 2000
Posts: 27
Recently there was a discussion about whether "JAVARANCH" would print immeadiately (no hesitation despite the sleep) or not. When I ran that code there indeed was no hesitation. However when I run the syncronized example code at Jyothi Krishnan's website on the following page: www.geocities.com/SiliconValley/Network/3693/obj_sec7.html#obj22
The sleep DOES cause a hesitation. I have revisted both sets of code and can't decide why one causes a hesitation and the other does not. Can someone explain this?
Here is Jyothi's code:
class Callme {
synchronized void call(String msg) {
System.out.print("[" + msg);
try Thread.sleep(1000);
catch (Exception e);
System.out.println("]");
}
}
class caller implements Runnable {
String msg;
Callme target;
public caller(Callme t, String s) {
target = t;
msg = s;
new Thread(this).start();
}
public void run() {
target.call(msg);
}
}
class Synch1 {
public static void main(String args[]) {
Callme target = new Callme();
new caller(target, "Hello");
new caller(target, "Synchronized");
new caller(target, "World");
}
}

Thanks in advance,
Lisa
bill bozeman
Ranch Hand

Joined: Jun 30, 2000
Posts: 1070
I haven't seen the code in the other example you are talking about, the one without the pause, but this one causes a pause becuase the lock is obtained on the object when you tell it to sleep, and the sleep method does not release the lock.
When you look at the code, you are creating one object Callme, named target, and then you are starting 3 threads with this object. When you get to the synchronized code, the lock is obtained by the first thread, and then it sleeps, and then it goes out of the call and releases the lock. If you took the synchronized keyword out of this, then it would not pause at all and all three words would print without hesitation.
Also, if you created 3 Callme objects, target1, target2, target3, then you would not have the hesitation even with the synchronized keyword, because you have 3 differnt objects so they do lock that object, but that doesn't conflict with the other 2 threads, since they are different objects.
So the key here is that it is the same object in all 3 threads, and it is synchrozied, thus the hesitation.
Hope that helps,
Bill
Lisa Yanchunis
Greenhorn

Joined: Nov 03, 2000
Posts: 27
That is it exactly, I had missed that the other code created two objects.... Sometimes its just right before your eyes.
Thanks
Lisa
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Threads and sleep