Discussion - the powerfull way to excellence!
Originally posted by Shahnawaz Shakil:
Hi Ram,
wait and notify are not alternative to synchronized. Infact wait(), notify() and notifyAll() should be called from within a synchronized context! A thread can't invoke a wait or notify method on an object unless it owns that object's lock.
Discussion - the powerfull way to excellence!
Originally posted by Shahnawaz Shakil:
Before i give you example i think we should be very clear about syncronized, wait and notify.
You can synchronize one or more method of a class (actually even just a block of code but leave it for now). When you synchronize a method it means you are telling the JVM that a thread needs to acquire the lock of the object before it can call this method. Since an object can have only one lock so if a thread is accessing a synchronized method, then no thread can access any of the synchronised method of that object. Though they can call those methods of the object which are not synchronized.Typically, releasing the lock means the thread holding the lock (the thread currently in the synchronized method) exits the synchronized method. At that point, the lock is free until some other thread enters a synchronized method on that object.
Now to understand wait() and notify() you can refer following example which is easy to understand. Here we have two classes named ThreadA and ThreadB. The main method in class ThreadA is printing the sum of i starting from 0 to 100. But this calculation is being done in the run() method of class ThreadB. So obviously main() method should wait for run() to complete so that it can print the total. Here comes the use of wait() method. And now you can understand why wait and notify should by called in synchronized context. When the thread waits it temporarily releases the lock for other threads to use but it will need it again to continue its execution. So once the thread which is waiting is notified (by notified method) it then starts comepting to acquire lock so that it can complete the remaining part of the method.
[code]
1. class ThreadA {
2. public static void main(String [] args) {
3. ThreadB b = new ThreadB();
4. b.start();
5.
6. synchronized(b) {
7. try {
8. System.out.println("Waiting for b to complete...");
9. b.wait();
10. } catch (InterruptedException e) {}
11. }
12. System.out.println("Total is: " + b.total);
13. }
14. }
15.
16. class ThreadB extends Thread {
17. int total;
18.
19. public void run() {
20. synchronized(this) {
21. for(int i=0;i<100;i++) {
22. total += i;
23. }
24. notify();
25. }
26. }
27. }
[code]
Hope this is helpful
Discussion - the powerfull way to excellence!
SCJP6