File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Undetermined result with wait/notify

 
Joyce Lee
Ranch Hand
Posts: 1392
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
Please bear with me and take sometime to read the following code...
-----
class ThreadA {
public synchronized static void main(String [] args) {
ThreadB b = new ThreadB();
b.start();
synchronized(b) {
try {
System.out.println("Waiting for b to complete...");
b.wait();
//b.wait(10); // to wake after the time has been expired
} catch (InterruptedException e) {}
}
System.out.println("Total is: " + b.total);
}
}
class ThreadB extends Thread {
int total;
public void run() {
synchronized(this) {
for(int i=0;i<3;i++) {
total += i; // total should be 3
}
notify();
}
}
}
If everything "turns out" ok, the notify() in run() will notify the main thread after the total value is processed and "3" will be printed out. But there's another scenario, that is, after b.start(), the scheduler may let the new thread to run until it's dead before switching back to the main thread. In this case, the main thread will be hanging there forever waiting to be notified.
In exam, will it expect us to determine the output result for code similar to the preceding one? If so, what is the correct answer for the preceding code:
1. 3
2. no output
If a reasonable time is given to the wait such that after the given time if it hasn't received any notification, it will wake up itself. Then the output result is definitely a "3".
Many thanks in advance for any input.
Cheers,
Joyce
 
Damien Howard
Ranch Hand
Posts: 456
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The correct answer is choice c) The output cannot be determined.
Although I'm not sure if you can synchronize on the main method.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic