• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What's the answer?

 
jianfeng shi
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
and whether it's print "XY" with a 1 second delay between X and Y.
 
jianfeng shi
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
and whether it's print "XY" with a 1 second delay between X and Y.
 
Henry Wong
author
Marshal
Pie
Posts: 21489
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
jianfeng shi
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21489
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Henry Wong very much
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic