MULTITHREADING
MULTITHREADING IN JAVA
• Multithreading in Java is a process of executing multiple threads
simultaneously.
• A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve
multitasking.
ADVANTAGES OF JAVA MULTITHREADING
1) It doesn't block the user because threads are independent and you
can perform multiple operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an
exception occurs in a single thread.
A THREAD IS A LIGHTWEIGHT SUBPROCESS, THE SMALLEST UNIT OF PROCESSING. IT IS A
SEPARATE PATH OF EXECUTION.
THREADS ARE INDEPENDENT. IF THERE OCCURS EXCEPTION IN ONE THREAD, IT DOESN'T
AFFECT OTHER THREADS. IT USES A SHARED MEMORY AREA.
JAVA THREAD METHODS:
S.N. Modifier and Type Method Description
1) void start() It is used to start the execution of the thread.
2) void run() It is used to do an action for a thread.
3) static void sleep() It sleeps a thread for the specified amount of time.
4) static Thread currentThread() It returns a reference to the currently executing thread object.
CONTD.
5) void join() It waits for a thread to die.
6) int getPriority() It returns the priority of the thread.
7) void setPriority() It changes the priority of the thread.
8) String getName() It returns the name of the thread.
9) void setName() It changes the name of the thread.
CONTD.
10) long getId() It returns the id of the thread.
11) boolean isAlive() It tests if the thread is alive.
12) static void yield() It causes the currently executing thread object to pause and allow other threads to
execute temporarily.
13) void suspend() It is used to suspend the thread.
14) void resume() It is used to resume the suspended thread.
LIFE CYCLE OF A THREAD (THREAD STATES):
THE LIFE CYCLE OF THE THREAD IN JAVA IS CONTROLLED BY JVM. THE
JAVA THREAD STATES ARE AS FOLLOWS:
THREAD STATES:
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. This state is also known as ready to run state and its waiting to
be selected by the schedular for running. When the thread goes in to
running state then run() method is called.
3)Running: The thread is in running state if the thread scheduler has
selected it for execution.
CONTD:
4) Non-Runnable (Blocked):
This is the state when the thread is still alive, but is currently not eligible
to [Link] are three conditions that cause a thread to go into a
non-Runnable state i.e Sleeping, waiting and blocked
5) Terminated or Dead:
A thread is in terminated or dead state when its run() method exits.
Once the thread is dead, you can not call its start() method again.
THREAD CREATION: when a java programs begins execution, it
always has atleast one thread i.e the main thread. Java provides two ways to
make your class behave as a thread.
❖ By Extending a [Link] class and override its run() method.
❖ By implementing the Runnable interface and implementing its run() method
Constructor purpose
Thread() Creates an instance of the Thread class
Thread(String name) Creates a Thread object and assigns a specified name to the
thread
Thread(Runnable target) Creates a new Thread object that uses the run() method of the
specified target
JAVA THREAD EXAMPLE BY EXTENDING
THREAD CLASS
class Multi extends Thread{
public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
[Link]();
}
}
CREATING THREAD USING THREAD CLASS
CONTD.
EXAMPLE:
JAVA THREAD EXAMPLE BY IMPLEMENTING
RUNNABLE INTERFACE
class Multi3 implements Runnable{ If you are not extending the
public void run(){ Thread class, your class object
would not be treated as a thread
[Link]("thread is running.
.."); }
object. So you need to explicitely
create Thread class [Link] are
public static void main(String args[]
passing the object of your class
){
that implements Runnable so that
Multi3 m1=new Multi3(); your class run() method may
Thread t1 =new Thread(m1); execute.
[Link](); }
}
EXAMPLE:
EXAMPLE OF EXTENDING THREAD CLASS:
CONTD.
CONTD.
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.
CONTD.
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 int getPriority(): [Link]() method
returns priority of given thread.
2. public final void setPriority(int
newPriority): [Link]() 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
// Default 5
[Link]("t1 thread priority : "
// Java program to demonstrate getPriority() and + [Link]());
// setPriority()
import [Link].*; // Default 5
[Link]("t2 thread priority : "
class ThreadDemo extends Thread { + [Link]());
public void run()
{ // Default 5
[Link]("Inside run method"); [Link]("t3 thread priority : "
} + [Link]());
public static void main(String[] args) [Link](2);
{ [Link](5);
ThreadDemo t1 = new ThreadDemo(); [Link](8);
ThreadDemo t2 = new ThreadDemo();
ThreadDemo t3 = new ThreadDemo();
CONTD.
// [Link](21); will throw // Main thread
// IllegalArgumentException // Displays the name of
// currently executing Thread
// 2 [Link](
[Link]("t1 thread priority : " "Currently Executing Thread : "
+ [Link]()); + [Link]()
.getName());
// 5 [Link](
[Link]("t2 thread priority : " "Main thread priority : "
+ [Link]()); + [Link]().getPriority());
// 8 // Main thread priority is set to 10
[Link]("t3 thread priority : " [Link]().setPriority(10);
+ [Link]()); [Link](
"Main thread priority : "
+ [Link]().getPriority());
}
}
CONTD.
• 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 then t3.
• Default priority for main thread is always 5, it can be changed later.
Default priority for all other threads depends on the priority of parent
thread.
Java program to demonstrate that a child thread gets same priority as
parent:
import [Link].*;
ThreadDemo t1 = new ThreadDemo();
class ThreadDemo extends Thread { // t1 thread is child of main thread
public void run()
{
// so t1 thread will also have priority 6.
[Link]("Inside run method"); [Link]("t1 thread priority : "
} + [Link]());
}
public static void main(String[] args) }
{
// main thread priority is 6 now
[Link]().setPriority(6);
[Link](
"main thread priority : "
+ [Link]().getPriority());
CONTD:
• 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 thread priority.
EXAMPLE:
CONTD.
ISALIVE() METHOD
// Java program to illustrate
// isAlive()
public static void main(String[] args)
public class oneThread extends Thread { {
public void run() oneThread c1 = new oneThread();
{ oneThread c2 = new oneThread();
[Link]("geeks "); [Link]();
try { [Link]();
[Link](300); [Link]([Link]());
} [Link]([Link]());
catch (InterruptedException ie) { }
} }
[Link]("forgeeks ");
}
JOIN() METHOD:
public static void main(String[] args)
{
public class oneThread extends Thread { oneThread c1 = new oneThread();
public void run() oneThread c2 = new oneThread();
{ [Link]();
[Link]("geeks ");
try { try {
[Link](300); [Link](); // Waiting for c1 to finish
} }
catch (InterruptedException ie) { catch (InterruptedException ie) {
} }
[Link]("forgeeks ");
} [Link]();
}
}
THANK YOU