[go: up one dir, main page]

0% found this document useful (0 votes)
28 views30 pages

JAVA MOD 4 NOTES_updated

Module 4 covers the concept of multithreading in Java, explaining the Java Thread Model, thread states, priorities, synchronization, and how to create threads. It details the life cycle of threads, methods for thread creation, and the importance of the main() method in Java programs. Additionally, it discusses thread priority and provides examples of how to manage thread execution and communication.

Uploaded by

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

JAVA MOD 4 NOTES_updated

Module 4 covers the concept of multithreading in Java, explaining the Java Thread Model, thread states, priorities, synchronization, and how to create threads. It details the life cycle of threads, methods for thread creation, and the importance of the main() method in Java programs. Additionally, it discusses thread priority and provides examples of how to manage thread execution and communication.

Uploaded by

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

SYLLABUS-MODULE 4

Multi Threading: Thread Concept,Java Thread Model, The main method, Creating Threads, Thread
Priorities, Synchronization,join

A multithreaded program contains two or moreparts that can run concurrently. Each part of such a program is
called a thread,and each thread defines a separate path of execution. Thus, multithreading is aspecialized form
of multitasking.there are two distinct typesof multitasking: process-based and thread-based. It is important to
understand thedifference between the two. For most readers, process-based multitasking is the morefamiliar
form. A process is, in essence, a program that is executing. Thus, process-basedmultitasking is the feature that
allows your computer to run two or more programsconcurrently. For example, process-based multitasking
enables you to run the Javacompiler at the same time that you are using a text editor. In process-based
multitasking,a program is the smallest unit of code that can be dispatched by the scheduler.In a thread-based
multitasking environment, the thread is the smallest unit ofdispatchable code. This means that a single program
can perform two or more taskssimultaneously. For instance, a text editor can format text at the same time that it
isprinting, as long as these two actions are being performed by two separate threads.Thus, process-based
multitasking deals with the “big picture,” and thread-basedmultitasking handles the details.

The Java Thread Model:


The Java run-time system depends on threads for many things, and all the class librariesare designed with
multithreading in mind. In fact, Java uses threads to enable theentire environment to be asynchronous. This
helps reduce inefficiency by preventingthe waste of CPU cycles.
As the process has several states, similarly a thread exists in several states. A thread can be in the following
states:
Life cycle of a Thread (Thread States)

A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java new,
runnable, non-runnable and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:

1. New
2. Runnable
3. Running
4. Non-Runnable(Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of start() method.

2) Runnable

The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected
it to be the running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable(Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated

A thread is in terminated or dead state when its run() method exits.

Java thread model can be defined in the following three sections:

Thread Priorities
Java Module-4 Notes

Each thread has its own priority in Java. Thread priority is an absolute integer value. Thread priority decides
only when a thread switches from one running thread to next, called context switching. Priority does increase
the running time of the thread or gives faster execution.
A thread can voluntarily relinquish control: This is done by explicitly yielding,sleeping, or blocking on
pending I/O. In this scenario, all other threads areexamined, and the highest-priority thread that is ready to run
is given the CPU.
A thread can be preempted by a higher-priority thread: In this case, a lower-prioritythread that does not
yield the processor is simply preempted—no matter whatit is doing—by a higher-priority thread. Basically, as
soon as a higher-prioritythread wants to run, it does. This is called preemptive multitasking.

Synchronization
Java supports an asynchronous multithreading, any number of thread can run simultaneously without disturbing
other to access individual resources at different instant of time or shareable resources. But some time it may be
possible that shareable resources are used by at least two threads or more than two threads, one has to write at
the same time, or one has to write and other thread is in the middle of reading it. For such type of situations and
circumstances Java implements synchronization model called monitor. The monitor is considered as a box, in
which only one thread can reside. As a thread enter in monitor, all other threads have to wait until that thread
exits from the monitor. In such a way, a monitor protects the shareable resources used by it being manipulated
by other waiting threads at the same instant of time. Java provides a simple methodology to
implementsynchronization.

Messaging
A program is a collection of more than one thread. Threads can communicate with each other. Java supports
messaging between the threads with lost-cost. It provides methods to all objects for inter-thread
communication. As a thread exits from synchronization state, it notifies all the waiting threads.

Threads in Java

How to create thread

There are two ways to create a thread:

1. By extending Threadclass
2. By implementing Runnableinterface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends
Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

o Thread()
o Thread(Stringname)
Java Module-4 Notes

o Thread(Runnabler)
o Thread(Runnable r,Stringname)

Commonly used methods of Thread class:

1. public void run(): is used to perform action for athread.


2. public void start(): starts the execution of the thread.JVM calls the run() method on thethread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarilycease
execution) for the specified number ofmilliseconds.
4. public void join(): waits for a thread todie.
5. public void join(long miliseconds): waits for a thread to die for the specifiedmiliseconds.
6. publicintgetPriority(): returns the priority of thethread.
7. publicintsetPriority(int priority): changes the priority of thethread.
8. public String getName(): returns the name of thethread.
9. public void setName(String name): changes the name of thethread.
10. public Thread currentThread(): returns the reference of currently executingthread.
Java Module-4 Notes

11. publicintgetId(): returns the id of thethread.


12. publicThread.StategetState(): returns the state of thethread.
13. publicbooleanisAlive(): tests if the thread isalive.
14. publicvoidyield():causes thecurrentlyexecutingthreadobjecttotemporarilypauseandallowother threads
toexecute.
15. public void suspend(): is used to suspend thethread(depricated).
16. public void resume(): is used to resume the suspendedthread(depricated).
17. public void stop(): is used to stop thethread(depricated).

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be executed by a
thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.

Starting a thread:

start() method of Thread class is used to start a newly created thread. It performs following tasks:
o A new thread starts(with newcallstack).
o The thread moves from New state to the Runnablestate.
o When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Threadclass

classMulti extends Thread{


public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Java Module-4 Notes

Output:
thread is running...

2) Java Thread Example by implementing Runnableinterface

classMulti3 implements Runnable{


public void run(){
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output:
thread is running...
//program to print thread names or to check threads created
packagelabpgms;
class A12 implements Runnable
{
publicvoid run()
{
System.out.println("Inside run method in A class");
}
}
publicclassthrconstructorextends Thread {
publicvoidrun()
{
System.out.println("Inside run method in main class");
}
publicstaticvoid main(String[] args) {

System.out.println(Thread.currentThread().getName());
thrconstructort1=newthrconstructor();
t1.start();
System.out.println(t1.getName());
A12 a=newA12();
Thread t=newThread(a);
t.start();
System.out.println(t.getName());
Thread t2=newThread();
System.out.println(t2.getName());
}

Java main() method

The main() is the starting point for JVM to start execution of a Java program. Without the main()
Java Module-4 Notes

method, JVM will not execute the program. The syntax of the main() method is:

public:It is an access specifier. We should use a public keyword before the main() method so that
JVM can identify the execution point of the program. If we use private, protected, and default before
the main() method, it will not be visible to JVM.

static:You can make a method static by using the keyword static. We should call the main() method
without creating an object. Static methods are the method which invokes without creating the objects,
so we do not need any object to call the main() method.

void:In Java, every method has the return type. Void keyword acknowledges the compiler that main()
method does not return any value.
main():It is a default signature which is predefined in the JVM. It is called by JVM to execute a
program line by line and end the execution after completion of this method. We can also overload the
main() method.

String args[]:The main() method also accepts some data from the user. It accepts a group of strings,
which is called a string array. It is used to hold the command line arguments in the form of string
values.

1. main(String args[])

Here, agrs[] is the array name, and it is of String type. It means that it can store a group of string.
Remember, this array can also store a group of numbers but in the form of string only. Values passed
to the main() method is called arguments. These arguments are stored into args[] array, so the name
args[] is generally used for it.

What happens if the main() method is written without String args[]?

The program will compile, but not run, because JVM will not recognize the main() method. Remember
JVM always looks for the main() method with a string type array as a parameter.

Execution Process

First, JVM executes the static block, then it executes static methods, and then it creates the object
needed by the program. Finally, it executes the instance methods. JVM executes a static block on the
highest priority basis. It means JVM first goes to static block even before it looks for the main()
method in the program.
Java Module-4 Notes

Example

classDemo
{
static //static block
{
System.out.println("Static block");
}
public static void main(String args[]) //static method
{
System.out.println("Static method");
}
}

Output:

S
t
a
t
i
c

b
l
o
c
k

S
t
a
t
i
c

m
e
t
h
o
d
Java Module-4 Notes

We observe that JVM first executes the static block, if it is present in the program. After that it
searches for the main() method. If the main() method is not found, it gives error.

Example

A program that does not have the main() method gives an error at run time.

1. classDemoStaticBlock
2.{
3. Static //static block
4.{
5. System.out.println("Staticblock");
6.}
7. }

Output:

Error: Main method not found in the


class Demo, please define the main
method as: public static void
main(String[]
So the main() args)
method should always be written as:
or a JavaFX application class must extend
javafx.application.Application
public static void main(String args[])

We can interchange public and static and write it as follows:

static public void main(String args[])

We can also use the different name for the String type array and write it as:

static public void main(String[] x)

Different ways of writing main() method are:

static public void main(String []x)


static public void main(String...args)

String...args: It allows the method to accept zero or multiple arguments. There should be exactly three
dots between String and array; otherwise, it gives an error.

Overloading of main() method

We can also overload the main() method. We can define any number of main() method in the class, but
the method signature must be different.

Example

classOverloadMain
{
Java Module-4 Notes

public static void main(inta) //overloaded main method


{
System.out.println(a);
}
public static void main(String args[])
{
System.out.println("main method incoked");
main(6);
}
}

Output:

mainmethodinvoked
6

Java Thread Priority in Multithreading


In a Multi threading environment, thread scheduler assigns processor to a thread based on priority of
thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either
be given by JVM while creating the thread or it can be given by programmer explicitly.
Accepted value of priority for a thread is in range of 1 to 10. There are 3 static variables defined in Thread
class for priority.
public static int MIN_PRIORITY: This is minimum priority that a thread can have. Value for this is 1.

public static int NORM_PRIORITY: This is default priority of a thread if do not explicitly define it.
Value for this is 5.

public static int MAX_PRIORITY: This is maximum priority of a thread. Value for this is 10.

Get and Set Thread Priority:

1. public final intgetPriority(): java.lang.Thread.getPriority() method returns priority of giventhread.

2. public final void setPriority(intnewPriority): java.lang.Thread.setPriority() method changes the


priority of thread to the value newPriority. This method throws IllegalArgumentException if value of
parameter newPriority goes beyond minimum(1) and maximum(10)limit.

Examples of getPriority() and set

// Java program to demonstrate getPriority() and setPriority()

packagelabpgms;
class A1 extends Thread
{
publicvoidrun()
{
for(inti=0;i<5;i++)
System.out.println("Inside run method in class A");
Java Module-4 Notes

}
}
class B1 extends Thread
{
publicvoidrun()
{
for(inti=0;i<5;i++)
System.out.println("Inside run method in class B");

}
}

publicclassthrpriorityextends Thread {
publicvoidrun()
{
for(inti=0;i<5;i++)
System.out.println("Inside run method thrpriority");
}
publicstaticvoid main(String[] args) {

thrpriorityt1 = newthrpriority();
A1 t2=newA1();
B1 t3=newB1();
System.out.println("t1 thread priority : " +t1.getPriority());
System.out.println("t2 thread priority : " +t2.getPriority());
System.out.println("t3 thread priority : " +t3.getPriority());
t1.start();
t2.start();
t3.start();
t2.setPriority(10);
t3.setPriority(5);
t1.setPriority(1);

//t3.setPriority(21); will throw IllegalArgumentException


System.out.println("t1 thread priority : " +t1.getPriority());
System.out.println("t2 thread priority : " +t2.getPriority());
System.out.println("t3 thread priority : " +t3.getPriority());

// Main thread
System.out.println(Thread.currentThread().getName());
System.out.println("Main thread priority : "+
Thread.currentThread().getPriority());
// Main thread priority is set to 10
Thread.currentThread().setPriority(10);
System.out.println("Main thread priority : "+
Thread.currentThread().getPriority());
Java Module-4 Notes

}
OUTPUT:
t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
Inside run method thrpriority
Inside run method thrpriority
Inside run method thrpriority
Inside run method thrpriority
Inside run method thrpriority
Inside run method in class A
Inside run method in class A
Inside run method in class A
t1 thread priority : 5
t2 thread priority : 10
t3 thread priority : 5
main
Main thread priority : 5
Main thread priority : 10
Inside run method in class B
Inside run method in class B
Inside run method in class B
Inside run method in class B
Inside run method in class B

Note:
 Thread with highest priority will get execution chance prior to other threads. Suppose there are 3
threads t1, t2 and t3 with priorities 4, 6 and 1. So, thread t2 will execute first based on maximum
priority 6 after that t1 will execute and thent3.
 Default priority for main thread is always 5, it can be changed later. Default priority for allother
threads depends on the priority of parentthread.

Example:
// Java program to demonstratethat a child thread
// gets same priority as parent
import java.lang.*;

classThreadDemo extends Thread


{
public void run()
{
System.out.println("Inside run method");
}
Java Module-4 Notes

public static void main(String[]args)


{
// main thread priority is 6 now
Thread.currentThread().setPriority(6);

System.out.println("main thread priority : " +


Thread.currentThread().getPriority());

ThreadDemo t1 = new ThreadDemo();


// t1 thread is child of main thread
// so t1 thread will also have priority 6.
System.out.println("t1 thread priority : "
+ t1.getPriority());
}
}
Output:
Main thread priority : 6
t1 thread priority : 6
 If two threads have same priority then we can’t expect which thread will execute first. It depends on
thread scheduler’s algorithm(Round-Robin, First Come First Serve,etc)
 If we are using thread priority for thread scheduling then we should always keep in mind that
underlying platform should provide support for scheduling based on threadpriority.

Synchronization in Java

Synchronization in java is the capability to control the access of multiple threads to any shared resource.

Java Synchronization is better option where we want to allow only one thread to access the shared
resource.

Why use Synchronization

The synchronization is mainly used to

1. To prevent threadinterference.
2. To prevent consistencyproblem.

Types of Synchronization

There are two types of synchronization

1. ProcessSynchronization
2. ThreadSynchronization

Here, we will discuss only thread synchronization.


Java Module-4 Notes

Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.

1. MutualExclusive
1. Synchronizedmethod.
2. Synchronizedblock.
3. staticsynchronization.
2. Cooperation (Inter-thread communication injava)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be
done by three ways in java:

1. by synchronizedmethod
2. by synchronizedblock
3. by staticsynchronization

Concept of Lock in Java

Synchronization is built around an internal entity known as the lock or monitor. Every object has an lock
associatedwithit.Byconvention,athreadthat needsconsistent access toanobject'sfieldshastoacquire the
object's lock before accessing them, and then release the lock when it's done withthem.

From Java 5 the package java.util.concurrent.locks contains several lock implementations.

Understanding the problem without Synchronization

In this example, there is no synchronization, so output is inconsistent. Let's see the example:

classTable{
voidprintTable(intn){//method not synchronized
for(inti=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}

}
}
Java Module-4 Notes

classMyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}

}
classMyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}

classTestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
100
10
200
15
300
20
400
25
500

Java synchronized method

If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for that object and
releases it when the thread completes its task.
Java Module-4 Notes

//example of java synchronized method


class Table{
synchronized void printTable(intn){//synchronized method
for(inti=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}

}
}

classMyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}

}
classMyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}

public class TestSynchronization2{


public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
Java Module-4 Notes

25
100
200
300
400
500

Sleep method in java

The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

Syntax of sleep() method in java

The Thread class provides two methods for sleeping a thread:

o public static void sleep(long miliseconds)throwsInterruptedException


o public static void sleep(long miliseconds, intnanos)throwsInterruptedException

Example of sleep method injava

classTestSleepMethod1 extends Thread{


public void run(){
for(inti=1;i<5;i++){
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();

t1.start();
t2.start();
}
Java Module-4 Notes

Output:

1
1
2
2
3
3
4
4

The join() method

Java.lang.Thread class provides the join() method which allows one thread to wait until another thread completes
its execution. If t is a Thread object whose thread is currently executing, then t.join() will make sure that t is
terminated before the next instruction is executed by the program.
If there are multiple threads calling the join() methods that means overloading on join allows the programmer to
specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume
that join will wait exactly as long as you specify.
Syntax:

public void join()throws InterruptedException


public void join(long milliseconds)throws InterruptedException

publicclassjoinexampleextends Thread{
publicvoidrun(){
for(inti=1;i<20;i++){

System.out.println(Thread.currentThread().getName()
);
System.out.println(i);
}
}
publicstaticvoid main(String args[]){
joinexamplet1=newjoinexample();
joinexamplet2=newjoinexample();
joinexamplet3=newjoinexample();
t1.start();
try
{

t1.join(); //or t1.join(1500);


}
catch(Exception e)
{
System.out.println(e);
}
t2.start();
try
{
Java Module-4 Notes

t2.join(); //or t2.join(1500);

}
catch(Exception e)
{
System.out.println(e);
}
t3.start();
try
{

t3.join(); //or t3.join(1500);

}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:

Thread-0
1
Thread-0
2
Thread-0
3
Thread-0
4
Thread-0
5
Thread-1
1
Thread-1
2
Thread-1
3
Thread-1
4
Thread-1
5
Thread-2
1
Thread-2
2
Thread-2
3
Thread-2
4
Thread-2
5

The above output clearly shows that t1 is executed then t2 and then t3.
Java Module-4 Notes

getName(),setName(String) and getId() method:

public String getName()


public void setName(String name)
public long getId()

classTestJoinMethod3 extends Thread{


public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestJoinMethod3 t1=new TestJoinMethod3();
TestJoinMethod3 t2=new TestJoinMethod3();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
System.out.println("id of t1:"+t1.getId());

t1.start();
t2.start();

t1.setName("SonooJaiswal");
System.out.println("After changing name of t1:"+t1.getName());
}
}
Output:
N
a
m
e

o
f

t
1
:
T
h
r
e
a
d
-
0

N
a
m
e

o
f
Java Module-4 Notes

The currentThread() method:

The currentThread() method returns a reference to the currently executing thread object.

Syntax:

public static Thread currentThread()

Example of currentThread() method

classTestJoinMethod4 extends Thread{


public void run(){
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String args[]){
TestJoinMethod4 t1=new TestJoinMethod4();
TestJoinMethod4 t2=new TestJoinMethod4();

t1.start();
t2.start();
}
}

Output:
T
h Thread and Current Thread
Naming
r
e
a
d Thread
Naming
-
The 0Thread class provides methods to change and get the name of a thread. By default, each thread has a
name i.e. thread-0, thread-1 and so on. By we can change the name of the thread by using setName()
T The syntax of setName() and getName() methods are given below:
method.
h
r
1. public String getName(): is used to return the name of athread.
e
2.
a public void setName(String name): is used to change the name of athread.
d
-
Example of naming a thread
1
classTestMultiNaming1 extends Thread{
public void run(){
Java Module-4 Notes

System.out.println("running...");
}
public static void main(String args[]){
TestMultiNaming1 t1=new TestMultiNaming1();
TestMultiNaming1 t2=new TestMultiNaming1();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());

t1.start();
t2.start();

t1.setName("SonooJaiswal");
System.out.println("After changing name of t1:"+t1.getName());
}
}

Output:
Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changeling name of t1:SonooJaiswal
running...

Current Thread

The currentThread() method returns a reference of currently executing thread.

public static Thread currentThread()

Example of currentThread() method

classTestMultiNaming2 extends Thread{


public void run(){
System.out.println(Thread.currentThread().getName());
}
public static void main(String args[]){
TestMultiNaming2 t1=new TestMultiNaming2();
TestMultiNaming2 t2=new TestMultiNaming2();

t1.start();
t2.start();
}
}
Output:
Thread-0
Thread-1
Java Module-4 Notes

Using isAlive( ):
finalbooleanisAlive( )The isAlive( ) method returns
true if the thread upon which it is called is still
running.It returns false otherwise.

packagelabpgms;

publicclassisaliveexampleextends Thread{
publicvoidrun()
{
for(inti=1;i<=5;i++){
System.out.println(i);
}
}

publicstaticvoid main(String args[])


{
isaliveexamplet1=newisaliveexample();
System.out.println("before t1.start() "+t1.isAlive());
t1.start();
System.out.println("after t1.start() "+t1.isAlive());
}
}

Output:
before t1.start() false
after t1.start() true
1
2
3
4
5

Interthread Communication:
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()
Java Module-4 Notes

1) 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.

public final void wait()throws InterruptedException waits until object is notified.

2) 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:

public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor. Syntax:

public final void notifyAll().

packagelabpgms;
classThreadBextends Thread {
inttotal;
publicvoidrun() {
for (inti = 0; i< 10; i++)
{
total += i;
}
}
}
publicclassThreadA
{
publicstaticvoid main(String[] args)
{
ThreadBb = newThreadB();
b.start();
System.out.println("Total is: " + b.total);

OUTPUT:
Java Module-4 Notes

Total is: 0

In the above program ,we want to print the total values calculate by ThreadB,

But due to parallel execution of threads,beforeThreadBexecutes,main thread


completes its execution printing the value of total to be 0.

The following program,synchronises the main and ThreadB,giving the updated value
of total as result.

Example program for inter Thread Communciation(Synchronised


block):

packagelabpgms;
classThreadBextends Thread{
inttotal;
publicvoidrun(){
synchronized(this)
{
for(inti=0; i<5 ; i++)
{
total += i;

notify();
}
}
}}
publicclassintercommunicationexample {
publicstaticvoid main(String[] args){
ThreadBb = newThreadB();
b.start();
synchronized(b)
{
try{
System.out.println("Waiting for b to complete...");
b.wait(); //wait() tells the calling thread to give up the monitor
//and go to sleep until some other thread enters the same monitor
//and calls notify( ).
}
catch(InterruptedExceptione){
e.printStackTrace();
}
System.out.println("Total is: " + b.total);
}
}}
Java Module-4 Notes

OUTPUT:

Waiting for b to complete...


Total is: 10

Producer-Consumer Program using Threads:


Problem
To make sure that the producer won’t try to add data into the buffer if it’s full and that the consumer won’t try to
remove data from an empty buffer.

Solution
The producer is to either go to sleep or discard data if the buffer is full. The next time the consumer removes
an item from the buffer, it notifies the producer, who starts to fill the buffer again. In the same way, the
consumer can go to sleep if it finds the buffer to be empty. The next time the producer puts data into the buffer,
it wakes up the sleeping consumer.
An inadequate solution could result in a deadlock where both processes are waiting to be awakened.
packagelabpgms;
class Q
{
intn;
booleanvalueSet = false;
synchronizedint get()
{
if(!valueSet)
try {
wait();
} catch(InterruptedExceptione) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
returnn;
}
synchronizedvoid put(intn) {
if(valueSet)
try {
wait();
} catch(InterruptedExceptione) {
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
if(n<=5)
Java Module-4 Notes

{
System.out.println("Put: " + n);
notify();
}}
}
class Producer extends Thread
{
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
publicvoidrun() {
inti = 1;
while(true) {
q.put(i++);
}
}
}
class Consumer extends Thread
{
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
publicvoidrun() {
while(true) {
q.get();
}
}
}
classproducerconsumer {
publicstaticvoid main(String args[]) {
System.out.println("Press Control-C to stop.");
Q q = newQ();
Producer p1=newProducer(q);
Consumer c1=newConsumer(q);
}
}

OUTPUT:

Press Control-C to stop.


Put: 1
Got: 1
Put: 2
Java Module-4 Notes

Got: 2
Put: 3
Got: 3
Put: 4
Got: 4
Put: 5
Got: 5

Java Garbage Collection

In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words,
it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is performed
automatically. So, java provides better memory management.

Advantage of Garbage Collection

o It makes java memory efficient because garbage collector removes the unreferenced objects
from heapmemory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need tomake
extraefforts.

How can an object be unreferenced?

There are many ways:

o By nulling thereference
o By assigning a reference toanother
o By anonymous objectetc.

1) By nulling areference:

1. Employee e=newEmployee();
2. e=null;

2) By assigning a reference toanother:

1. Employee e1=newEmployee();
2. Employee e2=newEmployee();
3. e1=e2;//now the first object referred by e1 is available for garbagecollection
Java Module-4 Notes

By anonymousobject:1. new Employee();

finalize() method

The finalize() method is invoked each time before the object is garbage collected. This method can be
used to perform cleanup processing. This method is defined in Object class as:

protected void finalize(){}

Note: The Garbage collector of JVM collects only


those objects that are created by new keyword. So
if you have created any object without new, you
can use finalize method to perform cleanup
processing (destroying remaining objects).

gc() method

The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is
found in System and Runtime classes.

public static void gc(){}

Note: Garbage collection is performed by a


daemon thread called Garbage Collector(GC).
This thread calls the finalize() method before
object is garbage collected.

Simple Example of garbage collection in java

public class TestGarbage1{


public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Java Module-4 Notes

Output:
object is garbage collected
object is garbage collected
Note: Neither finalization nor garbage collection is guaranteed.

You might also like