aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes What's the answer? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "What Watch "What New topic
Author

What's the answer?

jianfeng shi
Greenhorn

Joined: Mar 01, 2007
Posts: 8
public static synchronized void main(String[] args) throws InterruptedException
{
Thread t = new Thread();
t.start();
synchronized(t)
{
System.out.print("X");
try
{
t.wait(1000);
}catch(InterruptedException e){}
System.out.print("Y");
}
}
What's the result of this code
jianfeng shi
Greenhorn

Joined: Mar 01, 2007
Posts: 8
and whether it's print "XY" with a 1 second delay between X and Y.
jianfeng shi
Greenhorn

Joined: Mar 01, 2007
Posts: 8
and whether it's print "XY" with a 1 second delay between X and Y.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18963
    
  40

Originally posted by jianfeng shi:
and whether it's print "XY" with a 1 second delay between X and Y.


Well, this question will definitely *not* appear on the test, because you need implementation knowledge to answer this.

First, whether there will be a delay or not... it actually depends. The lib actually uses the Thread object to implement the join() method. So...

If the main thread grabs the lock (so it can wait), before the run() method of the new thread finishes and signals to that it finished, then the wait() method will receive the notification and return immediately.

On the other hand, if the new thread finishes and signals it completion, before the main method grabs the lock, then the main method will wait.


Second, in the example, no thread is sending the interruption, so "Y" should not even be printed.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
jianfeng shi
Greenhorn

Joined: Mar 01, 2007
Posts: 8
Thanks for your replay
but in my computer it's output "XY", and there is no delay between "X" and "Y".
my jdk is jdk1.5.0_12-b04.
I still have some doubt
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18963
    
  40

Originally posted by jianfeng shi:
Thanks for your replay
but in my computer it's output "XY", and there is no delay between "X" and "Y".
my jdk is jdk1.5.0_12-b04.
I still have some doubt


Please ignore my second point -- I misread the location of the bracket.

As for the first point -- it is machine dependant.

Henry
jianfeng shi
Greenhorn

Joined: Mar 01, 2007
Posts: 8
Thanks Henry Wong very much
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: What's the answer?