SlideShare a Scribd company logo
Core Java
Multithreading
Mr Jayant Dalvi
Multithreading : Summary
• A thread is a lightweight sub-process, the smallest
unit of processing. Multiprocessing and
multithreading, both are used to achieve
multitasking.
• Multithreading in Java is a process of executing
multiple threads simultaneously.
• we use multithreading than multiprocessing
because threads use a shared memory area. They
don't allocate separate memory area so saves
memory
• 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.
• Note: At a time one thread is executed only.
Advantages of Multithreading
• It doesn't block the user because threads are independent and you
can perform multiple operations at the same time.
• You can perform many operations together, so it saves time.
• Threads are independent, so it doesn't affect other threads if an
exception occurs in a single thread.
program: 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
• 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.
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();
}
}
Join() method
• The join() method waits for a thread
to die. In other words, it causes the
currently running threads to stop
executing until the thread it joins
with completes its task.
• Syntax:
• public void join()throws
InterruptedException
• public void join(long
milliseconds)throws
InterruptedException
class TestJoinMethod1 extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestJoinMethod1 t1=new TestJoinMethod1();
TestJoinMethod1 t2=new TestJoinMethod1();
TestJoinMethod1 t3=new TestJoinMethod1();
t1.start();
try{
t1.join();
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
}
Program of performing two tasks by two threads
class Simple1 extends Thread{
public void run(){
System.out.println("task one");
}
}
class Simple2 extends Thread{
public void run(){
System.out.println("task two");
}
}
class TestMultitasking3{
public static void main(String
args[]){
Simple1 t1=new Simple1();
Simple2 t2=new Simple2();
t1.start();
t2.start();
}
}
Synchronization
• 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.
Inter Thread 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:
• wait()
• notify()
• notifyAll()
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.
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()
Process of InterThread Communication
• Threads enter to acquire lock.
• Lock is acquired by on thread.
• Now thread goes to waiting state if you call
wait() method on the object. Otherwise it
releases the lock and exits.
• If you call notify() or notifyAll() method,
thread moves to the notified state (runnable
state).
• Now thread is available to acquire lock.
• After completion of the task, thread releases
the lock and exits the monitor state of the
object.
Multithreading Important Questions
• Write a program that creates two threads. Each thread is instantiated from the same class. It executes a loop with
10 iterations. Each iteration displays “Welcome” message, sleeps for 200 milliseconds.
• Explain life cycle of thread
• What are different ways of creating a thread?
• What is purpose of wait() method in multithreading?
• What is multithreading? How to create Thread using Thread class?
• What is thread synchronization? How is it achieved in Java?
• List and explain methods used in inter thread communication
• What do you mean by synchronising a thread explain in detail
• What is meant by multithreading? Explain how to create thread using Runnable interface
• Write a note on Thread class and methods of thread class
• WAP to show interleaving of 2 threads and display output ABABABABABA

More Related Content

What's hot (20)

PPTX
Constructor in java
Hitesh Kumar
 
PDF
Java IO
UTSAB NEUPANE
 
PPTX
Packages in java
Elizabeth alexander
 
PPTX
Multithreading in java
Arafat Hossan
 
PDF
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
PPTX
Method overloading
Lovely Professional University
 
PDF
Methods in Java
Jussi Pohjolainen
 
PDF
Monitors
Mohd Arif
 
PDF
Java thread life cycle
Archana Gopinath
 
PDF
Applets
Prabhakaran V M
 
PPT
Java non access modifiers
Srinivas Reddy
 
PPTX
I/O Streams
Ravi Chythanya
 
PDF
Life cycle-of-a-thread
javaicon
 
PPTX
Control statements in java
Madishetty Prathibha
 
PDF
Java threads
Prabhakaran V M
 
ODP
Multithreading In Java
parag
 
PPT
08 state diagram and activity diagram
Baskarkncet
 
PPTX
Static Members-Java.pptx
ADDAGIRIVENKATARAVIC
 
PPTX
OOP - Java is pass-by-value
Mudasir Qazi
 
PPTX
Arrays,string and vector
Kavitha713564
 
Constructor in java
Hitesh Kumar
 
Java IO
UTSAB NEUPANE
 
Packages in java
Elizabeth alexander
 
Multithreading in java
Arafat Hossan
 
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
Method overloading
Lovely Professional University
 
Methods in Java
Jussi Pohjolainen
 
Monitors
Mohd Arif
 
Java thread life cycle
Archana Gopinath
 
Java non access modifiers
Srinivas Reddy
 
I/O Streams
Ravi Chythanya
 
Life cycle-of-a-thread
javaicon
 
Control statements in java
Madishetty Prathibha
 
Java threads
Prabhakaran V M
 
Multithreading In Java
parag
 
08 state diagram and activity diagram
Baskarkncet
 
Static Members-Java.pptx
ADDAGIRIVENKATARAVIC
 
OOP - Java is pass-by-value
Mudasir Qazi
 
Arrays,string and vector
Kavitha713564
 

Similar to Multithreading in Java (20)

PPTX
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
nimbalkarvikram966
 
PDF
Java Multithreading Interview Questions PDF By ScholarHat
Scholarhat
 
PPTX
Threads in Java
HarshaDokula
 
PPTX
Java programming PPT. .pptx
creativegamerz00
 
PPTX
unit-3java.pptx
sujatha629799
 
PPT
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
PPTX
Multi-threaded Programming in JAVA
Vikram Kalyani
 
DOCX
Module - 5 merged.docx notes about engineering subjects java
KaviShetty
 
PPTX
Chap3 multi threaded programming
raksharao
 
PPTX
Concept of Java Multithreading-Partially.pptx
SahilKumar542
 
PPTX
U4 JAVA.pptx
madan r
 
PPTX
Multithreading in java
Kavitha713564
 
PPTX
Multithreading in java
Kavitha713564
 
PPTX
multithreading.pptx
Sravanibitragunta
 
PPT
Thread
Juhi Kumari
 
PPTX
multithreading to be used in java with good programs.pptx
PriyadharshiniG41
 
PPTX
Multithreading in java
Lovely Professional University
 
PPT
Programming - Java-Threads-and-Synchronization.ppt
smychung
 
PDF
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
KusumitaSahoo1
 
PPTX
Inter Thread Communicationn.pptx
SelvakumarNSNS
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
nimbalkarvikram966
 
Java Multithreading Interview Questions PDF By ScholarHat
Scholarhat
 
Threads in Java
HarshaDokula
 
Java programming PPT. .pptx
creativegamerz00
 
unit-3java.pptx
sujatha629799
 
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Multi-threaded Programming in JAVA
Vikram Kalyani
 
Module - 5 merged.docx notes about engineering subjects java
KaviShetty
 
Chap3 multi threaded programming
raksharao
 
Concept of Java Multithreading-Partially.pptx
SahilKumar542
 
U4 JAVA.pptx
madan r
 
Multithreading in java
Kavitha713564
 
Multithreading in java
Kavitha713564
 
multithreading.pptx
Sravanibitragunta
 
Thread
Juhi Kumari
 
multithreading to be used in java with good programs.pptx
PriyadharshiniG41
 
Multithreading in java
Lovely Professional University
 
Programming - Java-Threads-and-Synchronization.ppt
smychung
 
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
KusumitaSahoo1
 
Inter Thread Communicationn.pptx
SelvakumarNSNS
 
Ad

More from Jayant Dalvi (16)

PPTX
Linux System Administration
Jayant Dalvi
 
PPTX
Linux System Administration
Jayant Dalvi
 
PPTX
Structured system analysis and design
Jayant Dalvi
 
PPTX
Structured system analysis and design
Jayant Dalvi
 
PPTX
Structured system analysis and design
Jayant Dalvi
 
PPTX
Java I/O
Jayant Dalvi
 
PPTX
Information system audit 2
Jayant Dalvi
 
PPTX
Structured system analysis and design
Jayant Dalvi
 
PPTX
java- Abstract Window toolkit
Jayant Dalvi
 
PPTX
Structured system analysis and design
Jayant Dalvi
 
PPTX
Information system audit
Jayant Dalvi
 
PPTX
Information system audit
Jayant Dalvi
 
PPTX
Structured system analysis and design
Jayant Dalvi
 
PPTX
Information system audit
Jayant Dalvi
 
PPTX
Exception handling c++
Jayant Dalvi
 
PPTX
Object Oriented Programming using C++
Jayant Dalvi
 
Linux System Administration
Jayant Dalvi
 
Linux System Administration
Jayant Dalvi
 
Structured system analysis and design
Jayant Dalvi
 
Structured system analysis and design
Jayant Dalvi
 
Structured system analysis and design
Jayant Dalvi
 
Java I/O
Jayant Dalvi
 
Information system audit 2
Jayant Dalvi
 
Structured system analysis and design
Jayant Dalvi
 
java- Abstract Window toolkit
Jayant Dalvi
 
Structured system analysis and design
Jayant Dalvi
 
Information system audit
Jayant Dalvi
 
Information system audit
Jayant Dalvi
 
Structured system analysis and design
Jayant Dalvi
 
Information system audit
Jayant Dalvi
 
Exception handling c++
Jayant Dalvi
 
Object Oriented Programming using C++
Jayant Dalvi
 
Ad

Recently uploaded (20)

PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
Dimensions of Societal Planning in Commonism
StefanMz
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 

Multithreading in Java

  • 2. Multithreading : Summary • A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. • Multithreading in Java is a process of executing multiple threads simultaneously. • we use multithreading than multiprocessing because threads use a shared memory area. They don't allocate separate memory area so saves memory • 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. • Note: At a time one thread is executed only.
  • 3. Advantages of Multithreading • It doesn't block the user because threads are independent and you can perform multiple operations at the same time. • You can perform many operations together, so it saves time. • Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
  • 4. program: 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(); } }
  • 5. Java Thread Example by implementing Runnable interface • 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. 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(); } }
  • 6. Join() method • The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task. • Syntax: • public void join()throws InterruptedException • public void join(long milliseconds)throws InterruptedException class TestJoinMethod1 extends Thread{ public void run(){ for(int i=1;i<=5;i++){ try{ Thread.sleep(500); }catch(Exception e){System.out.println(e);} System.out.println(i); } } public static void main(String args[]){ TestJoinMethod1 t1=new TestJoinMethod1(); TestJoinMethod1 t2=new TestJoinMethod1(); TestJoinMethod1 t3=new TestJoinMethod1(); t1.start(); try{ t1.join(); }catch(Exception e){System.out.println(e);} t2.start(); t3.start(); } }
  • 7. Program of performing two tasks by two threads class Simple1 extends Thread{ public void run(){ System.out.println("task one"); } } class Simple2 extends Thread{ public void run(){ System.out.println("task two"); } } class TestMultitasking3{ public static void main(String args[]){ Simple1 t1=new Simple1(); Simple2 t2=new Simple2(); t1.start(); t2.start(); } }
  • 8. Synchronization • 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.
  • 9. Inter Thread 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: • wait() • notify() • notifyAll()
  • 10. 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. 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()
  • 11. Process of InterThread Communication • Threads enter to acquire lock. • Lock is acquired by on thread. • Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the lock and exits. • If you call notify() or notifyAll() method, thread moves to the notified state (runnable state). • Now thread is available to acquire lock. • After completion of the task, thread releases the lock and exits the monitor state of the object.
  • 12. Multithreading Important Questions • Write a program that creates two threads. Each thread is instantiated from the same class. It executes a loop with 10 iterations. Each iteration displays “Welcome” message, sleeps for 200 milliseconds. • Explain life cycle of thread • What are different ways of creating a thread? • What is purpose of wait() method in multithreading? • What is multithreading? How to create Thread using Thread class? • What is thread synchronization? How is it achieved in Java? • List and explain methods used in inter thread communication • What do you mean by synchronising a thread explain in detail • What is meant by multithreading? Explain how to create thread using Runnable interface • Write a note on Thread class and methods of thread class • WAP to show interleaving of 2 threads and display output ABABABABABA