0% found this document useful (0 votes)
12 views

Inter thread communication

Ok

Uploaded by

gowdacharu91
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Inter thread communication

Ok

Uploaded by

gowdacharu91
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Inter-thread Communication in Java

Inter-thread communication or Co-operation is all about allowing


synchronized threads to communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a


thread is paused running in its critical section and another thread is
allowed to enter (or lock) in the same critical section to be executed.It
is implemented by following methods of Object class:

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.

Backward Skip 10sPlay VideoForward Skip 10s

Method Description

public final void wait()throws InterruptedException It waits until object is n

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:

1. public final void notify()


3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.

Syntax:

1. public final void notifyAll()

Understanding the process of inter-thread


communication

The point to point explanation of the above diagram is as follows:

1. Threads enter to acquire lock.


2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the
object. Otherwise it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the
notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits
the monitor state of the object.

Why wait(), notify() and notifyAll() methods are defined in


Object class not Thread class?
It is because they are related to lock and object has a lock.

Difference between wait and sleep?


Let's see the important differences between wait and sleep methods.

wait() sleep()

The wait() method releases the lock. The sleep() method doesn't
release the lock.

It is a method of Object class It is a method of Thread class

It is the non-static method It is the static method

It should be notified by notify() or notifyAll() After the specified amount of


methods time, sleep is completed.

Example of Inter Thread Communication in Java


Let's see the simple example of inter thread communication.

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

Wrapper classes in Java


The wrapper class in Java provides the mechanism to convert
primitive into object and object into primitive.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives
into objects and objects into primitives automatically. The automatic
conversion of primitive into an object is known as autoboxing and vice-
versa unboxing.

Use of Wrapper classes in Java


Java is an object-oriented programming language, so we need to deal
with objects many times like in Collections, Serialization,
Synchronization, etc. Let us see the different scenarios, where we need
to use the wrapper classes.

o Change the value in Method: Java supports only call by value.


So, if we pass a primitive value, it will not change the original
value. But, if we convert the primitive value in an object, it will
change the original value.
o Serialization: We need to convert the objects into streams to
perform the serialization. If we have a primitive value, we can
convert it in objects through the wrapper classes.
o Synchronization: Java synchronization works with objects in
Multithreading.
o java.util package: The java.util package provides the utility
classes to deal with objects.
o Collection Framework: Java collection framework works with
objects only. All classes of the collection framework (ArrayList,
LinkedList, Vector, HashSet, LinkedHashSet, TreeSet,
PriorityQueue, ArrayDeque, etc.) deal with objects only.

The eight classes of the java.lang package are known as wrapper


classes in Java. The list of eight wrapper classes are given below:

Primitive Type Wrapper class

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.

Since Java 5, we do not need to use the valueOf() method of wrapper


classes to convert the primitive into objects.

Wrapper class Example: Primitive to Wrapper

1. //Java program to convert primitive into objects


2. //Autoboxing example of int to Integer
3. public class WrapperExample1{
4. public static void main(String args[]){
5. //Converting int into Integer
6. int a=20;
7. Integer i=Integer.valueOf(a);//converting int into Integer explicitly
8. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) inte
rnally
9.
10. System.out.println(a+" "+i+" "+j);
11. }}

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.

Wrapper class Example: Wrapper to Primitive

1. //Java program to convert object into primitives


2. //Unboxing example of Integer to int
3. public class WrapperExample2{
4. public static void main(String args[]){
5. //Converting Integer to int
6. Integer a=new Integer(3);
7. int i=a.intValue();//converting Integer to int explicitly
8. int j=a;//unboxing, now compiler will write a.intValue() internally
9.
10. System.out.println(a+" "+i+" "+j);
11. }}

Output:

3 3 3

Java Wrapper classes Example


1. //Java Program to convert all primitives into its corresponding
2. //wrapper objects and vice-versa
3. public class WrapperExample3{
4. public static void main(String args[]){
5. byte b=10;
6. short s=20;
7. int i=30;
8. long l=40;
9. float f=50.0F;
10. double d=60.0D;
11. char c='a';
12. boolean b2=true;
13.
14. //Autoboxing: Converting primitives into objects
15. Byte byteobj=b;
16. Short shortobj=s;
17. Integer intobj=i;
18. Long longobj=l;
19. Float floatobj=f;
20. Double doubleobj=d;
21. Character charobj=c;
22. Boolean boolobj=b2;
23.
24. //Printing objects
25. System.out.println("---Printing object values---");
26. System.out.println("Byte object: "+byteobj);
27. System.out.println("Short object: "+shortobj);
28. System.out.println("Integer object: "+intobj);
29. System.out.println("Long object: "+longobj);
30. System.out.println("Float object: "+floatobj);
31. System.out.println("Double object: "+doubleobj);
32. System.out.println("Character object: "+charobj);
33. System.out.println("Boolean object: "+boolobj);
34.
35. //Unboxing: Converting Objects to Primitives
36. byte bytevalue=byteobj;
37. short shortvalue=shortobj;
38. int intvalue=intobj;
39. long longvalue=longobj;
40. float floatvalue=floatobj;
41. double doublevalue=doubleobj;
42. char charvalue=charobj;
43. boolean boolvalue=boolobj;
44.
45. //Printing primitives
46. System.out.println("---Printing primitive values---");
47. System.out.println("byte value: "+bytevalue);
48. System.out.println("short value: "+shortvalue);
49. System.out.println("int value: "+intvalue);
50. System.out.println("long value: "+longvalue);
51. System.out.println("float value: "+floatvalue);
52. System.out.println("double value: "+doublevalue);
53. System.out.println("char value: "+charvalue);
54. System.out.println("boolean value: "+boolvalue);
55. }}

Output:

---Printing object values---


Byte object: 10
Short object: 20
Integer object: 30
Long object: 40
Float object: 50.0
Double object: 60.0
Character object: a
Boolean object: true
---Printing primitive values---
byte value: 10
short value: 20
int value: 30
long value: 40
float value: 50.0
double value: 60.0
char value: a
boolean value: true

Custom Wrapper class in Java


Java Wrapper classes wrap the primitive data types, that is why it is
known as wrapper classes. We can also create a class which wraps a
primitive data type. So, we can create a custom wrapper class in Java.

1. //Creating the custom wrapper class


2. class Javatpoint{
3. private int i;
4. Javatpoint(){}
5. Javatpoint(int i){
6. this.i=i;
7. }
8. public int getValue(){
9. return i;
10. }
11. public void setValue(int i){
12. this.i=i;
13. }
14. @Override
15. public String toString() {
16. return Integer.toString(i);
17. }
18. }
19. //Testing the custom wrapper class
20. public class TestJavatpoint{
21. public static void main(String[] args){
22. Javatpoint j=new Javatpoint(10);
23. System.out.println(j);
24. }}

Output:

10

You might also like