Multithreading in Java 5
Interthread Communication
Java provide benefit of avoiding thread pooling using interthread communication. The wait(), notify(), notifyAll() of Object class. These method are implemented as final in Object.
All three method can be called only from within a synchronized context :
1) wait() tells calling thread to give up monitor and go to sleep until some other thread enters the same monitor and call notify.
2) notify() wakes up a thread that called wait() on same object.
Syntax : public final void notify()
3) notifyAll() wakes up all the thread that called wait() on same object.
Syntax : public final void notifyAll()
Difference between wait( ) and sleep( )
wait( ) | sleep( ) |
wait() method releases the lock sleep(). | method doesn't release the lock. |
called from synchronised block. | no such requirement. |
method of Object class. | method of Thread class. |
Throw is used within the method. | Throws is used with the method signature. |
awake when notify() or notifyAll() method is called. | not awake when notify() or notifyAll() method is called. |
not a static method. | static method. |
wait() is generaly used on condition. | sleep() method is simply used to put your thread on sleep. |
Thread Pooling
Pooling is usually implemented by loop i.e to check some condition repeatedly. Once condition is true appropriate action is taken. This waste CPU time.
Example of inter thread communication in java
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amountSystem
wait();
}catch(Exception e){} }
this.amount-=amount; System.out.println("withdraw completed..."); } synchronized void deposit(int amount){ System.out.println("going to deposit..."); this.amount+=amount; System.out.println("deposit completed... "); notify(); } } class Test{ public static void main(String args[]){ final Customer c=new Customer(); new Thread(){ public void run(){
c.withdraw(15000);
} }.start();
new Thread(){ public void run(){c.deposit(10000);
} }.start(); }
}
Output: going to withdraw... Less balance; waiting for deposit... going to deposit... deposit completed... withdraw completed