Inter thread communication
Inter thread communication
o wait()
o notify()
o notifyAll()
1) wait() method
The wait() method causes current thread to release the lock and wait
until either another thread invokes the notify() method or the notifyAll()
method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called
from the synchronized method only otherwise it will throw exception.
Method Description
public final void wait(long timeout)throws InterruptedException It waits for the specifie
2) notify() method
The notify() method wakes up a single thread that is waiting on this
object's monitor. If any threads are waiting on this object, one of them
is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation.
Syntax:
Syntax:
wait() sleep()
The wait() method releases the lock. The sleep() method doesn't
release the lock.
Test.java
1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
16. System.out.println("going to deposit...");
17. this.amount+=amount;
18. System.out.println("deposit completed... ");
19. notify();
20. }
21. }
22.
23. class Test{
24. public static void main(String args[]){
25. final Customer c=new Customer();
26. new Thread(){
27. public void run(){c.withdraw(15000);}
28. }.start();
29. new Thread(){
30. public void run(){c.deposit(10000);}
31. }.start();
32.
33. }}
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Autoboxing
The automatic conversion of primitive data type into its corresponding
wrapper class is known as autoboxing, for example, byte to Byte, char
to Character, int to Integer, long to Long, float to Float, boolean to
Boolean, double to Double, and short to Short.
Output:
20 20 20
Unboxing
The automatic conversion of wrapper type into its corresponding
primitive type is known as unboxing. It is the reverse process of
autoboxing. Since Java 5, we do not need to use the intValue() method
of wrapper classes to convert the wrapper type into primitives.
Output:
3 3 3
Output:
Output:
10