SlideShare a Scribd company logo
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.
However, we use multithreading than multiprocessing because threads use a shared
memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
Java Multithreading is mostly used in games, animation, etc.
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.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved in two ways:
Process-based Multitasking (Multiprocessing)
Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
Each process has an address in memory. In other words, each process allocates a separate
memory area.
A process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
Threads share the same address space.
A thread is lightweight.
Cost of communication between the thread is low.
What is Thread in java
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.
As shown in the below figure, a thread is executed inside the
process. There is context-switching between the threads. There can
be multiple processes inside the OS, and one process can have
multiple threads.
Java Thread class
Java provides Thread class to achieve
thread programming. Thread class provides
constructors and methods to create and
perform operations on a thread. Thread class
extends Object class and implements
Runnable interface.
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming language
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:
New
Runnable
Running
Non-Runnable (Blocked)
Terminated
Multithreading in Java Object Oriented Programming language
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.
How to create thread
There are two ways to create a thread:
By extending Thread class
By implementing Runnable interface.
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:
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
Commonly used methods of Thread class:
public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution)
for the specified number of milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of the thread.
public Thread currentThread(): returns the reference of currently executing thread.
public int getId(): returns the id of the thread.
public Thread.State getState(): returns the state of the thread.
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to
execute.
public void suspend(): is used to suspend the thread(depricated).
public void resume(): is used to resume the suspended thread(depricated).
public void stop(): is used to stop the thread(depricated).
public boolean isDaemon(): tests if the thread is a daemon thread.
public void setDaemon(boolean b): marks the thread as daemon or user thread.
public void interrupt(): interrupts the thread.
public boolean isInterrupted(): tests if the thread has been interrupted.
public static boolean interrupted(): tests if the current thread has been interrupted.
Java Thread Example by extending Thread class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Java Thread Example by implementing Runnable interface
class Multi3 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();
}
}
If you are not extending the Thread class, your class object would not be treated as a thread
object.So you need to explicitely create Thread class object. We are passing the object of
your class that implements Runnable so that your class run() method may execute.
Using the Thread Class: Thread(String Name)
We can directly use the Thread class to spawn new threads using the constructors defined
above.
1.public class MyThread1
2.{
3.// Main method
4.public static void main(String argvs[])
5.{
6.// creating an object of the Thread class using the constructor Thread(String name)
7.Thread t= new Thread("My first thread");
8.
9.// the start() method moves the thread to the active state
10.t.start();
11.// getting the thread name by invoking the getName() method
12.String str = t.getName();
13.System.out.println(str);
14.}
15.}
Using the Thread Class: Thread(Runnable r, String name)
1.public class MyThread2 implements Runnable
2.{
3.public void run()
4.{
5.System.out.println("Now the thread is running ...");
6.}
7. // main method
8.public static void main(String argvs[])
9.{
10.// creating an object of the class MyThread2
11.Runnable r1 = new MyThread2();
12.
13.// creating an object of the class Thread using Thread(Runnable r, String name)
14.Thread th1 = new Thread(r1, "My new thread");
15. // the start() method moves the thread to the active state
16.th1.start();
17. // getting the thread name by invoking the getName() method
18.String str = th1.getName();
19.System.out.println(str);
20.}
21.}
Thread Scheduler in Java
Thread scheduler in java is the part of the JVM that decides which thread should run.
There is no guarantee that which runnable thread will be chosen to run by the thread
scheduler.
Only one thread at a time can run in a single process.
The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the
threads.
Difference between preemptive scheduling and time slicing
Under preemptive scheduling, the highest priority task executes until it enters the waiting or
dead states or a higher priority task comes into existence. Under time slicing, a task
executes for a predefined slice of time and then reenters the pool of ready tasks. The
scheduler then determines which task should execute next, based on priority and other
factors.
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:
public static void sleep(long miliseconds)throws InterruptedException
public static void sleep(long miliseconds, int nanos)throws InterruptedException
Example of sleep method in java
class TestSleepMethod1 extends Thread{
public void run(){
for(int i=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();
}
}
As you know well that at a time only one thread is executed. If you sleep a thread for the
specified time,the thread shedular picks up another thread and so on.
Example of the sleep() Method in Java : on the main thread
1.// important import statements
2.import java.lang.Thread;
3.import java.io.*;
4.public class TestSleepMethod2
5.{
6. // main method
7.public static void main(String argvs[])
8.{
9. try {
10.for (int j = 0; j < 5; j++)
11.{
12.// The main thread sleeps for the 1000 milliseconds, which is 1 sec
13.// whenever the loop runs
14.Thread.sleep(1000);
15. // displaying the value of the variable
16.System.out.println(j);
17.} }
18.catch (Exception expn)
19.{
20.// catching the exception
21.System.out.println(expn);
22.}
23.}
Example of the sleep() Method in Java: When the sleeping time is -ive
The following example throws the exception IllegalArguementException when the time for
sleeping is negative.
1./ important import statements
2.import java.lang.Thread;
3.import java.io.*;
4. public class TestSleepMethod3
5.{ // main method
6.public static void main(String argvs[]) {
7.// we can also use throws keyword followed by // exception name for throwing the excep
tion
8.try {
9.for (int j = 0; j < 5; j++) {
10.// it throws the exception IllegalArgumentException // as the time is -ive which is -100
11.Thread.sleep(-100);
12.// displaying the variable's value
13.System.out.println(j); } }
14.catch (Exception expn) { // the exception iscaught here
15.System.out.println(expn);
16.}
17.}
18.}
// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread
{ public void run()
{ try
{ // Displaying the thread that is running
System.out.println ("Thread " + Thread.currentThread().getId() +
" is running"); }
catch (Exception e) {
// Throwing an exception
System.out.println ("Exception is caught"); }
} }
// Main Class
public class Multithread{
public static void main(String[] args) {
int n = 8; // Number of threads
for (int i=0; i<8; i++) {
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}}}
Can we start a thread twice
No. After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown. In such case, thread will run once but for
second time, it will throw exception.
Let's understand it by the example given below:
public class TestThreadTwice1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestThreadTwice1 t1=new TestThreadTwice1();
t1.start();
t1.start();
}
}
Naming Thread and Current Thread
class TestMultiNaming1 extends Thread{
public void run(){
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("Sonoo Jaiswal");
System.out.println("After changing name of t1:"+t1.getName());
}
}
Example of currentThread() method
class TestMultiNaming2 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();
}
}
Priority of a Thread (Thread Priority):
Each thread have a priority. Priorities are represented by a number between 1
and 10. In most cases, thread schedular schedules the threads according to
their priority (known as preemptive scheduling). But it is not guaranteed
because it depends on JVM specification that which scheduling it chooses.
3 constants defined in Thread class:
1. public static int MIN_PRIORITY
2.public static int NORM_PRIORITY
3.public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY
is 1 and the value of MAX_PRIORITY is 10.
Example of priority of a Thread:
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getNa
me());
System.out.println("running thread priority is:"+Thread.currentThread().getPri
ority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Daemon Thread in Java
Daemon thread in java is a service provider thread that provides services to
the user thread. Its life depend on the mercy of user threads i.e. when all the
user threads dies, JVM terminates this thread automatically.
There are many java daemon threads running automatically e.g. gc, finalizer
etc.
You can see all the detail by typing the jconsole in the command prompt. The
jconsole tool provides information about the loaded classes, memory usage,
running threads etc.
Points to remember for Daemon Thread in Java
• It provides services to user threads for background supporting tasks. It has
no role in life than to serve user threads.
• Its life depends on user threads.
• It is a low priority thread.
Why JVM terminates the daemon thread if there is no user thread?
The sole purpose of the daemon thread is that it provides services to user
thread for background supporting task. If there is no user thread, why should
JVM keep running this thread. That is why JVM terminates the daemon thread if
there is no user thread.
Methods for Java Daemon thread by Thread class
The java.lang.Thread class provides two methods for java daemon thread.
No. Method Description
1) public void
setDaemon(boolean
status)
is used to mark the
current thread as
daemon thread or user
thread.
2) public boolean
isDaemon()
is used to check that
current is daemon.
Simple example of Daemon thread in java
public class TestDaemonThread1 extends Thread{
public void run(){
if(Thread.currentThread().isDaemon()){//checking for daemon thread
System.out.println("daemon thread work");
}
else{
System.out.println("user thread work");
}
}
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.setDaemon(true);//now t1 is daemon thread
t1.start();//starting threads
t2.start();
t3.start();
}
}
Note: If you want to make a user thread as Daemon, it must not be started otherwise it will
throw IllegalThreadStateException.
1.class TestDaemonThread2 extends Thread{
2. public void run(){
3. System.out.println("Name: "+Thread.currentThread().getName());
4. System.out.println("Daemon: "+Thread.currentThread().isDaemon());
5. }
6.
7. public static void main(String[] args){
8. TestDaemonThread2 t1=new TestDaemonThread2();
9. TestDaemonThread2 t2=new TestDaemonThread2();
10. t1.start();
11. t1.setDaemon(true);//will throw exception here
12. t2.start();
13. }
14.}
Output: Output:exception in thread main: java.lang.IllegalThreadStateException
join() method
• The join() method in Java is provided by the
java.lang.
• Thread class that permits one thread to wait
until the other thread to finish its execution.
• Suppose th be the object the class Thread
whose thread is doing its execution currently,
then the th.join(); statement ensures that th is
finished before the program does the execution
of the next statement.
• When there are more than one thread invoking
the join() method, then it leads to overloading on
the join() method that permits the developer or
programmer to mention the waiting period.
1.class TestJoinMethod1 extends Thread{
2. public void run(){
3. for(int i=1;i<=5;i++){
4. try{
5. Thread.sleep(500);
6. }catch(Exception e){System.out.println(e);}
7. System.out.println(i);
8. } }
9.public static void main(String args[]){
10. TestJoinMethod1 t1=new TestJoinMethod1();
11. TestJoinMethod1 t2=new TestJoinMethod1();
12. TestJoinMethod1 t3=new TestJoinMethod1();
13. t1.start();
14. try{
15. t1.join();
16. }catch(Exception e){System.out.println(e);}
17. t2.start();
18. t3.start();
19. }
20.}
Java Thread Synchronization
In multithreading, there is the asynchronous behavior of the programs. If one thread is
writing some data and another thread which is reading data at the same time, might create
inconsistency in the application.
When there is a need to access the shared resources by two or more threads, then
synchronization approach is utilized.
Java has provided synchronized methods to implement synchronized behavior.
In this approach, once the thread reaches inside the synchronized block, then no other
thread can call that method on the same object. All threads have to wait till that thread
finishes the synchronized block and comes out of that.
In this way, the synchronization helps in a multithreaded application. One thread has to wait
till other thread finishes its execution only then the other threads are allowed for execution.
It can be written in the following form:
Synchronized(object) { //Block of statements to be synchronized }
Why use Synchronization
The synchronization is mainly used to
To prevent thread interference.
To prevent consistency problem.
Types of Synchronization
There are two types of synchronization
Process Synchronization
Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
Mutual Exclusive
Synchronized method.
Synchronized block.
static synchronization.
Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data.
This can be done by three ways in java:
by synchronized method
by synchronized block
by static synchronization
Understanding the problem without Synchronization
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);} }}}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;}
public void run(){
t.printTable(5); } }
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t; }
public void run(){
t.printTable(100); }}
class TestSynchronization1{
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
//example of java synchronized method
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);} } } }
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t; }
public void run(){
t.printTable(5); } }
class MyThread2 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 25 100 200 300 400 500
References
https://www.javatpoint.com/java-tutorial
https://www.tutorialspoint.com/java/index.htm
https://www.oreilly.com/library/view/java-the-complete/9781259589348/

More Related Content

PDF
Heuristic Search in Artificial Intelligence | Heuristic Function in AI | Admi...
RahulSharma4566
 
PPTX
Java awt (abstract window toolkit)
Elizabeth alexander
 
PPT
Array in Java
Shehrevar Davierwala
 
PPTX
Inter Thread Communicationn.pptx
SelvakumarNSNS
 
PDF
Files in java
Muthukumaran Subramanian
 
PPT
Unit 4 external sorting
DrkhanchanaR
 
PPTX
trigger dbms
kuldeep100
 
PDF
Data structure lab manual
nikshaikh786
 
Heuristic Search in Artificial Intelligence | Heuristic Function in AI | Admi...
RahulSharma4566
 
Java awt (abstract window toolkit)
Elizabeth alexander
 
Array in Java
Shehrevar Davierwala
 
Inter Thread Communicationn.pptx
SelvakumarNSNS
 
Unit 4 external sorting
DrkhanchanaR
 
trigger dbms
kuldeep100
 
Data structure lab manual
nikshaikh786
 

What's hot (20)

PPTX
Strings in Java
Abhilash Nair
 
PPTX
Regular Expressions in Java
OblivionWalker
 
DOCX
Play fair cipher
Khawar Abbas
 
PPTX
Java Queue.pptx
vishal choudhary
 
PDF
Inner Classes in Java
Dallington Asingwire
 
PDF
An Introduction to Programming in Java: Arrays
Martin Chapman
 
PPT
JDBC – Java Database Connectivity
Information Technology
 
PPTX
Access specifiers(modifiers) in java
HrithikShinde
 
PPTX
Java Quiz
Dharmraj Sharma
 
PPTX
File handling
priya_trehan
 
PPT
Bucket sort
Toto MZiri
 
PDF
Arrays in Java
Naz Abdalla
 
PPTX
Exception handling in Java
Abhishek Pachisia
 
PPTX
Java GC
Ray Cheng
 
PPTX
Circular queue
Lovely Professional University
 
PPTX
Packages and interfaces
bhuvaneshwariA5
 
PPTX
L21 io streams
teach4uin
 
PPTX
L14 string handling(string buffer class)
teach4uin
 
DOCX
Data Structure in C (Lab Programs)
Saket Pathak
 
Strings in Java
Abhilash Nair
 
Regular Expressions in Java
OblivionWalker
 
Play fair cipher
Khawar Abbas
 
Java Queue.pptx
vishal choudhary
 
Inner Classes in Java
Dallington Asingwire
 
An Introduction to Programming in Java: Arrays
Martin Chapman
 
JDBC – Java Database Connectivity
Information Technology
 
Access specifiers(modifiers) in java
HrithikShinde
 
Java Quiz
Dharmraj Sharma
 
File handling
priya_trehan
 
Bucket sort
Toto MZiri
 
Arrays in Java
Naz Abdalla
 
Exception handling in Java
Abhishek Pachisia
 
Java GC
Ray Cheng
 
Packages and interfaces
bhuvaneshwariA5
 
L21 io streams
teach4uin
 
L14 string handling(string buffer class)
teach4uin
 
Data Structure in C (Lab Programs)
Saket Pathak
 
Ad

Similar to Multithreading in Java Object Oriented Programming language (20)

PPTX
Multi threading
Mavoori Soshmitha
 
PPTX
Concept of Java Multithreading-Partially.pptx
SahilKumar542
 
PPTX
Threads in Java
HarshaDokula
 
PPTX
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
nimbalkarvikram966
 
PDF
Java unit 12
Shipra Swati
 
PDF
Class notes(week 9) on multithreading
Kuntal Bhowmick
 
PPTX
multithreading,thread and processinjava-210302183809.pptx
ArunPatrick2
 
PDF
Java Multithreading Interview Questions PDF By ScholarHat
Scholarhat
 
PPTX
Multithreading in java
junnubabu
 
PDF
CSE 3146 M1- MULTI THREADING USING JAVA .pdf
universitypresidency
 
PPT
Thread model in java
AmbigaMurugesan
 
PPTX
Multithreading in java
Monika Mishra
 
PPTX
Multithreading in java
Arafat Hossan
 
PPT
BCA MultiThreading.ppt
sarthakgithub
 
PPTX
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 
PPT
Chap2 2 1
Hemo Chella
 
PDF
Java Threads
Hamid Ghorbani
 
PPTX
Slide 7 Thread-1.pptx
ajmalhamidi1380
 
PPT
multhi threading concept in oops through java
Parameshwar Maddela
 
PDF
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Multi threading
Mavoori Soshmitha
 
Concept of Java Multithreading-Partially.pptx
SahilKumar542
 
Threads in Java
HarshaDokula
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
nimbalkarvikram966
 
Java unit 12
Shipra Swati
 
Class notes(week 9) on multithreading
Kuntal Bhowmick
 
multithreading,thread and processinjava-210302183809.pptx
ArunPatrick2
 
Java Multithreading Interview Questions PDF By ScholarHat
Scholarhat
 
Multithreading in java
junnubabu
 
CSE 3146 M1- MULTI THREADING USING JAVA .pdf
universitypresidency
 
Thread model in java
AmbigaMurugesan
 
Multithreading in java
Monika Mishra
 
Multithreading in java
Arafat Hossan
 
BCA MultiThreading.ppt
sarthakgithub
 
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 
Chap2 2 1
Hemo Chella
 
Java Threads
Hamid Ghorbani
 
Slide 7 Thread-1.pptx
ajmalhamidi1380
 
multhi threading concept in oops through java
Parameshwar Maddela
 
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Ad

Recently uploaded (20)

PPTX
Trends in pediatric nursing .pptx
AneetaSharma15
 
PDF
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PDF
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
PDF
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PPT
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
DOCX
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
PPTX
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
PDF
Study Material and notes for Women Empowerment
ComputerScienceSACWC
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PPTX
FSSAI (Food Safety and Standards Authority of India) & FDA (Food and Drug Adm...
Dr. Paindla Jyothirmai
 
PPTX
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
DOCX
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
PPTX
CDH. pptx
AneetaSharma15
 
Trends in pediatric nursing .pptx
AneetaSharma15
 
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
Study Material and notes for Women Empowerment
ComputerScienceSACWC
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
FSSAI (Food Safety and Standards Authority of India) & FDA (Food and Drug Adm...
Dr. Paindla Jyothirmai
 
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
CDH. pptx
AneetaSharma15
 

Multithreading in Java Object Oriented Programming language

  • 1. 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. However, we use multithreading than multiprocessing because threads use a shared memory area. They don't allocate separate memory area so saves memory, and context- switching between the threads takes less time than process. Java Multithreading is mostly used in games, animation, etc.
  • 2. 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.
  • 3. Multitasking Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved in two ways: Process-based Multitasking (Multiprocessing) Thread-based Multitasking (Multithreading) 1) Process-based Multitasking (Multiprocessing) Each process has an address in memory. In other words, each process allocates a separate memory area. A process is heavyweight. Cost of communication between the process is high. Switching from one process to another requires some time for saving and loading registers, memory maps, updating lists, etc. 2) Thread-based Multitasking (Multithreading) Threads share the same address space. A thread is lightweight. Cost of communication between the thread is low.
  • 4. What is Thread in java 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.
  • 5. As shown in the below figure, a thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS, and one process can have multiple threads.
  • 6. Java Thread class Java provides Thread class to achieve thread programming. Thread class provides constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.
  • 9. 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: New Runnable Running Non-Runnable (Blocked) Terminated
  • 11. 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.
  • 12. How to create thread There are two ways to create a thread: By extending Thread class By implementing Runnable interface. 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: Thread() Thread(String name) Thread(Runnable r) Thread(Runnable r,String name)
  • 13. Commonly used methods of Thread class: public void run(): is used to perform action for a thread. public void start(): starts the execution of the thread.JVM calls the run() method on the thread. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. public void join(): waits for a thread to die. public void join(long miliseconds): waits for a thread to die for the specified miliseconds. public int getPriority(): returns the priority of the thread. public int setPriority(int priority): changes the priority of the thread. public String getName(): returns the name of the thread. public void setName(String name): changes the name of the thread. public Thread currentThread(): returns the reference of currently executing thread. public int getId(): returns the id of the thread. public Thread.State getState(): returns the state of the thread. public boolean isAlive(): tests if the thread is alive. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute. public void suspend(): is used to suspend the thread(depricated). public void resume(): is used to resume the suspended thread(depricated). public void stop(): is used to stop the thread(depricated). public boolean isDaemon(): tests if the thread is a daemon thread. public void setDaemon(boolean b): marks the thread as daemon or user thread. public void interrupt(): interrupts the thread. public boolean isInterrupted(): tests if the thread has been interrupted. public static boolean interrupted(): tests if the current thread has been interrupted.
  • 14. Java Thread Example by extending Thread class class Multi extends Thread{ public void run(){ System.out.println("thread is running..."); } public static void main(String args[]){ Multi t1=new Multi(); t1.start(); } }
  • 15. Java Thread Example by implementing Runnable interface class Multi3 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(); } } If you are not extending the Thread class, your class object would not be treated as a thread object.So you need to explicitely create Thread class object. We are passing the object of your class that implements Runnable so that your class run() method may execute.
  • 16. Using the Thread Class: Thread(String Name) We can directly use the Thread class to spawn new threads using the constructors defined above. 1.public class MyThread1 2.{ 3.// Main method 4.public static void main(String argvs[]) 5.{ 6.// creating an object of the Thread class using the constructor Thread(String name) 7.Thread t= new Thread("My first thread"); 8. 9.// the start() method moves the thread to the active state 10.t.start(); 11.// getting the thread name by invoking the getName() method 12.String str = t.getName(); 13.System.out.println(str); 14.} 15.}
  • 17. Using the Thread Class: Thread(Runnable r, String name) 1.public class MyThread2 implements Runnable 2.{ 3.public void run() 4.{ 5.System.out.println("Now the thread is running ..."); 6.} 7. // main method 8.public static void main(String argvs[]) 9.{ 10.// creating an object of the class MyThread2 11.Runnable r1 = new MyThread2(); 12. 13.// creating an object of the class Thread using Thread(Runnable r, String name) 14.Thread th1 = new Thread(r1, "My new thread"); 15. // the start() method moves the thread to the active state 16.th1.start(); 17. // getting the thread name by invoking the getName() method 18.String str = th1.getName(); 19.System.out.println(str); 20.} 21.}
  • 18. Thread Scheduler in Java Thread scheduler in java is the part of the JVM that decides which thread should run. There is no guarantee that which runnable thread will be chosen to run by the thread scheduler. Only one thread at a time can run in a single process. The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads. Difference between preemptive scheduling and time slicing Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
  • 19. 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: public static void sleep(long miliseconds)throws InterruptedException public static void sleep(long miliseconds, int nanos)throws InterruptedException
  • 20. Example of sleep method in java class TestSleepMethod1 extends Thread{ public void run(){ for(int i=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(); } } As you know well that at a time only one thread is executed. If you sleep a thread for the specified time,the thread shedular picks up another thread and so on.
  • 21. Example of the sleep() Method in Java : on the main thread 1.// important import statements 2.import java.lang.Thread; 3.import java.io.*; 4.public class TestSleepMethod2 5.{ 6. // main method 7.public static void main(String argvs[]) 8.{ 9. try { 10.for (int j = 0; j < 5; j++) 11.{ 12.// The main thread sleeps for the 1000 milliseconds, which is 1 sec 13.// whenever the loop runs 14.Thread.sleep(1000); 15. // displaying the value of the variable 16.System.out.println(j); 17.} } 18.catch (Exception expn) 19.{ 20.// catching the exception 21.System.out.println(expn); 22.} 23.}
  • 22. Example of the sleep() Method in Java: When the sleeping time is -ive The following example throws the exception IllegalArguementException when the time for sleeping is negative. 1./ important import statements 2.import java.lang.Thread; 3.import java.io.*; 4. public class TestSleepMethod3 5.{ // main method 6.public static void main(String argvs[]) { 7.// we can also use throws keyword followed by // exception name for throwing the excep tion 8.try { 9.for (int j = 0; j < 5; j++) { 10.// it throws the exception IllegalArgumentException // as the time is -ive which is -100 11.Thread.sleep(-100); 12.// displaying the variable's value 13.System.out.println(j); } } 14.catch (Exception expn) { // the exception iscaught here 15.System.out.println(expn); 16.} 17.} 18.}
  • 23. // Java code for thread creation by extending // the Thread class class MultithreadingDemo extends Thread { public void run() { try { // Displaying the thread that is running System.out.println ("Thread " + Thread.currentThread().getId() + " is running"); } catch (Exception e) { // Throwing an exception System.out.println ("Exception is caught"); } } } // Main Class public class Multithread{ public static void main(String[] args) { int n = 8; // Number of threads for (int i=0; i<8; i++) { MultithreadingDemo object = new MultithreadingDemo(); object.start(); }}}
  • 24. Can we start a thread twice No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception. Let's understand it by the example given below: public class TestThreadTwice1 extends Thread{ public void run(){ System.out.println("running..."); } public static void main(String args[]){ TestThreadTwice1 t1=new TestThreadTwice1(); t1.start(); t1.start(); } }
  • 25. Naming Thread and Current Thread class TestMultiNaming1 extends Thread{ public void run(){ 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("Sonoo Jaiswal"); System.out.println("After changing name of t1:"+t1.getName()); } }
  • 26. Example of currentThread() method class TestMultiNaming2 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(); } }
  • 27. Priority of a Thread (Thread Priority): Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread schedular schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses. 3 constants defined in Thread class: 1. public static int MIN_PRIORITY 2.public static int NORM_PRIORITY 3.public static int MAX_PRIORITY Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
  • 28. Example of priority of a Thread: class TestMultiPriority1 extends Thread{ public void run(){ System.out.println("running thread name is:"+Thread.currentThread().getNa me()); System.out.println("running thread priority is:"+Thread.currentThread().getPri ority()); } public static void main(String args[]){ TestMultiPriority1 m1=new TestMultiPriority1(); TestMultiPriority1 m2=new TestMultiPriority1(); m1.setPriority(Thread.MIN_PRIORITY); m2.setPriority(Thread.MAX_PRIORITY); m1.start(); m2.start(); } }
  • 29. Daemon Thread in Java Daemon thread in java is a service provider thread that provides services to the user thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically. There are many java daemon threads running automatically e.g. gc, finalizer etc. You can see all the detail by typing the jconsole in the command prompt. The jconsole tool provides information about the loaded classes, memory usage, running threads etc. Points to remember for Daemon Thread in Java • It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads. • Its life depends on user threads. • It is a low priority thread.
  • 30. Why JVM terminates the daemon thread if there is no user thread? The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread. Methods for Java Daemon thread by Thread class The java.lang.Thread class provides two methods for java daemon thread. No. Method Description 1) public void setDaemon(boolean status) is used to mark the current thread as daemon thread or user thread. 2) public boolean isDaemon() is used to check that current is daemon.
  • 31. Simple example of Daemon thread in java public class TestDaemonThread1 extends Thread{ public void run(){ if(Thread.currentThread().isDaemon()){//checking for daemon thread System.out.println("daemon thread work"); } else{ System.out.println("user thread work"); } } public static void main(String[] args){ TestDaemonThread1 t1=new TestDaemonThread1();//creating thread TestDaemonThread1 t2=new TestDaemonThread1(); TestDaemonThread1 t3=new TestDaemonThread1(); t1.setDaemon(true);//now t1 is daemon thread t1.start();//starting threads t2.start(); t3.start(); } }
  • 32. Note: If you want to make a user thread as Daemon, it must not be started otherwise it will throw IllegalThreadStateException. 1.class TestDaemonThread2 extends Thread{ 2. public void run(){ 3. System.out.println("Name: "+Thread.currentThread().getName()); 4. System.out.println("Daemon: "+Thread.currentThread().isDaemon()); 5. } 6. 7. public static void main(String[] args){ 8. TestDaemonThread2 t1=new TestDaemonThread2(); 9. TestDaemonThread2 t2=new TestDaemonThread2(); 10. t1.start(); 11. t1.setDaemon(true);//will throw exception here 12. t2.start(); 13. } 14.} Output: Output:exception in thread main: java.lang.IllegalThreadStateException
  • 33. join() method • The join() method in Java is provided by the java.lang. • Thread class that permits one thread to wait until the other thread to finish its execution. • Suppose th be the object the class Thread whose thread is doing its execution currently, then the th.join(); statement ensures that th is finished before the program does the execution of the next statement. • When there are more than one thread invoking the join() method, then it leads to overloading on the join() method that permits the developer or programmer to mention the waiting period.
  • 34. 1.class TestJoinMethod1 extends Thread{ 2. public void run(){ 3. for(int i=1;i<=5;i++){ 4. try{ 5. Thread.sleep(500); 6. }catch(Exception e){System.out.println(e);} 7. System.out.println(i); 8. } } 9.public static void main(String args[]){ 10. TestJoinMethod1 t1=new TestJoinMethod1(); 11. TestJoinMethod1 t2=new TestJoinMethod1(); 12. TestJoinMethod1 t3=new TestJoinMethod1(); 13. t1.start(); 14. try{ 15. t1.join(); 16. }catch(Exception e){System.out.println(e);} 17. t2.start(); 18. t3.start(); 19. } 20.}
  • 35. Java Thread Synchronization In multithreading, there is the asynchronous behavior of the programs. If one thread is writing some data and another thread which is reading data at the same time, might create inconsistency in the application. When there is a need to access the shared resources by two or more threads, then synchronization approach is utilized. Java has provided synchronized methods to implement synchronized behavior. In this approach, once the thread reaches inside the synchronized block, then no other thread can call that method on the same object. All threads have to wait till that thread finishes the synchronized block and comes out of that. In this way, the synchronization helps in a multithreaded application. One thread has to wait till other thread finishes its execution only then the other threads are allowed for execution. It can be written in the following form: Synchronized(object) { //Block of statements to be synchronized }
  • 36. Why use Synchronization The synchronization is mainly used to To prevent thread interference. To prevent consistency problem. Types of Synchronization There are two types of synchronization Process Synchronization Thread Synchronization Thread Synchronization There are two types of thread synchronization mutual exclusive and inter-thread communication. Mutual Exclusive Synchronized method. Synchronized block. static synchronization. Cooperation (Inter-thread communication in java)
  • 37. Mutual Exclusive Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by three ways in java: by synchronized method by synchronized block by static synchronization
  • 38. Understanding the problem without Synchronization class Table{ void printTable(int n){//method not synchronized for(int i=1;i<=5;i++){ System.out.println(n*i); try{ Thread.sleep(400); }catch(Exception e){System.out.println(e);} }}} class MyThread1 extends Thread{ Table t; MyThread1(Table t){ this.t=t;} public void run(){ t.printTable(5); } } class MyThread2 extends Thread{ Table t; MyThread2(Table t){ this.t=t; } public void run(){ t.printTable(100); }} class TestSynchronization1{ 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(); } }
  • 39. Output: 5 100 10 200 15 300 20 400 25 500
  • 40. Java synchronized method //example of java synchronized method class Table{ synchronized void printTable(int n){//synchronized method for(int i=1;i<=5;i++){ System.out.println(n*i); try{ Thread.sleep(400); }catch(Exception e){System.out.println(e);} } } } class MyThread1 extends Thread{ Table t; MyThread1(Table t){ this.t=t; } public void run(){ t.printTable(5); } } class MyThread2 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(); } }
  • 41. Output: 5 10 15 20 25 100 200 300 400 500