wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Undetermined result with wait/notify 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 "Undetermined result with wait/notify" Watch "Undetermined result with wait/notify" New topic
Author

Undetermined result with wait/notify

Joyce Lee
Ranch Hand

Joined: Jul 11, 2003
Posts: 1392
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

Joined: Apr 01, 2003
Posts: 456
The correct answer is choice c) The output cannot be determined.
Although I'm not sure if you can synchronize on the main method.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Undetermined result with wait/notify
 
Similar Threads
Confusing in wait notify
Using wait/notify()
Multithreading: How can total be nearly 5,000 even though loop is up to 100?
Problem On using wait() in THreads
wait and notify..test