hi i didn't understand the following stuff at all....
its from K&B.. and i read it many times ...
and after reading it 5-6 times ...
didnt clear it fully...
please anybody explain me ....here it goes
=============================================================Let’s take a look at some real code
that shows one object waiting for another object to notify it (take note, it is somewhat
complex):
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. }
This program contains two objects with threads: ThreadA contains the main thread
and ThreadB has a thread that calculates the sum of all numbers from 0 through 99.
As soon as line 4 calls the start() method, ThreadA will continue with the next
line of code in its own class, which means it could get to line 12 before ThreadB has
finished the calculation. To prevent this, we use the wait() method in line 9.
Notice in line 6 the code synchronizes itself with the object b—this is because in
order to call wait() on the object, ThreadA must own a lock on b. For a thread to
call wait() or notify(), the thread has to be the owner of the lock for that object.
When the thread waits, it temporarily releases the lock for other threads to use, but
it will need it again to continue execution. It is common to find code such as the
following:
synchronized(anotherObject) { // this has the lock on anotherObject
try {
anotherObject.wait();
// the thread releases the lock and waits
// To continue, the thread needs the lock,
// so it may be blocked until it gets it.
} catch(InterruptedException e){}
}
The preceding code waits until notify() is called on anotherObject.
synchronized(this) {
notify();
}
This code notifies any thread currently waiting on the this object.
The lock can be acquired much earlier in the code, such as in the calling method.
==============================================================
i will be gr8full