Hello Ranchers,
I have a doubt regarding the self
test question 16 in K&B 5.0
Please find the code below:
1. public class Test {
2. public static void main (
String [] args) {
3. final Foo f = new Foo();
4.
Thread t = new Thread(new Runnable() {
5. public void run() {
6. f.doStuff();
7. }
8. });
9. Thread g = new Thread() {
10. public void run() {
11. f.doStuff();
12. }
13. };
14. t.start();
15. g.start();
16. }
17. }
1. class Foo {
2. int x = 5;
3. public void doStuff() {
4. if (x < 10) {
5. // nothing to do
6. try {
7. wait();
8. } catch(InterruptedException ex) { }
9. } else {
10. System.out.println("x is " + x++);
11. if (x >= 10) {
12. notify();
13. }
14. }
15. }
16. }
Answer given is An Exception occurs at runtime.
my doubt is regarding the call to wait() method.
wait() method can be called only in synchronized context right.
But here in this example, there is a call to wait() method in a non synchronized method/block. But when i tried to compile the code in my
IDE, it compiles properly.
Can any one please explain me why the code given above compiles?
Thanks,Srilatha M