Win a copy of Pragmatic AI this week in the Artificial Intelligence forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Undetermined result with wait/notify  RSS feed

 
Ranch Hand
Posts: 1392
  • 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
 
Ranch Hand
Posts: 456
  • 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.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!