SlideShare a Scribd company logo
Darshan Institute of Engineering & Technology, Rajkot
Jayesh.vagadiya@darshan.ac.in
9537133260
Computer Engineering Department
Prof. Jayesh D. Vagadiya
Object Oriented Programming -I
(3140705)
Unit-12
Concurrency /
Multithreading
 Looping
Outline
Multithreading
Life Cycle of Thread
Creating a Thread
Using Thread Class
Using Runnable Interface
Join
Synchronized
Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 3
What is Multithreading?
 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.
 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.
 A thread goes through various stages in its life cycle. For example, a thread is
born, started, runs, and then dies.
 Lets see the life cycle of the thread.
Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 4
Life cycle of a Thread
 There are 5 stages in the life cycle of the
Thread
 New: A new thread begins its life cycle in the new
state. It remains in this state until the program
starts the thread. It is also referred to as a born
thread.
 Runnable: After a newly born thread is started, the
thread becomes runnable. A thread in this state is
considered to be executing its task.
 Waiting: Sometimes a thread transitions to the
waiting state while the thread waits for another
thread to perform a task. A thread transitions back
to the runnable state only when another thread
signals waiting thread to continue.
 Timed waiting: A runnable thread can enter the
timed waiting state for a specified interval of time. A
thread in this state transitions back to the runnable
state when that time interval expires or when the
event it is waiting for occurs.
 Terminated: A runnable thread enters the
new
runnable
timed
waiting
waiting
terminate
d
Program starts
thread
unlock
signal
signalAll
aw
ait
lock
await
sleep
Interval
expires
T
h
r
e
a
d
c
o
m
p
l
e
t
e
s
T
a
s
k
Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 5
Creating a Thread in Java
 There are two ways to create a Thread
1. extending the Thread class
2. implementing the Runnable interface
Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 6
1) Extending Thread Class
 One way to create a thread is to create a new class that extends Thread, and
then to create an instance of that class.
 The extending class must override the run( ) method, which is the entry point
for the new thread.
 It must also call start( ) to begin execution of the new thread.
class NewThread extends Thread {
NewThread() {
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}
public void run() {
try {
for (int i = 5; i > 0; i--) {
System.out.println("Child Thread: " +
i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}}
class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for (int i = 5; i > 0; i--) {
System.out.println("Main Thread: " +
i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread
interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 7
2) Implementing Runnable Interface
 To implement thread using Runnable interface, Runnable interface needs to
be implemented by the class.
class NewThread implements Runnable
 Class which implements Runnable interface should override the run() method
which containts the logic of the thread.
public void run( )
 Instance of Thread class is created using following constructor.
Thread(Runnable threadOb, String threadName);
 Here threadOb is an instance of a class that implements the Runnable
interface and the name of the new thread is specified by threadName.
 start() method of Thread class will invoke the run() method.
Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 8
Example Runnable Interface
Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 9
Thread using Executor Framework
 Steps to execute thread using Executor Framework are as follows:
1. Create a task (Runnable Object) to execute
2. Create Executor Pool using Executors
3. Pass tasks to Executor Pool
4. Shutdown the Executor Pool
Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 10
Example Executable Framework
class Task implements Runnable {
private String name;
public Task(String s) {
name = s;
}
public void run() {
try {
for (int i = 1; i<=5; i++)
{
System.out.println(nam
e+" - task number -
"+i);
Thread.sleep(1000);
}
System.out.println(name+"
complete");
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
}
import java.util.concurrent.*;
public class ExecutorThreadDemo {
public static void main(String[]
args) {
Runnable r1 = new Task("task
1");
Runnable r2 = new Task("task
2");
Runnable r3 = new Task("task
3");
Runnable r4 = new Task("task
4");
Runnable r5 = new Task("task
5");
ExecutorService pool =
Executors.newFixedThreadPool(3)
;
pool.execute(r1);
pool.execute(r2);
pool.execute(r3);
pool.execute(r4);
pool.execute(r5);
pool.shutdown();
}
}
Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 11
Thread Synchronization
 When we start two or more threads within a program, there may be a situation
when multiple threads try to access the same resource and finally they can
produce unforeseen result due to concurrency issues.
 For example, if multiple threads try to write within a same file then they may
corrupt the data because one of the threads can override data or while one
thread is opening the same file at the same time another thread might be
closing the same file.
 So there is a need to synchronize the action of multiple threads and make sure
that only one thread can access the resource at a given point in time.
 Java programming language provides a very handy way of creating threads and
synchronizing their task by using synchronized methods & synchronized blocks.
Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 12
Problem without synchronization (Example)
class Table {
void printTable(int n) {
for (int i = 1; i <= 5; i++) {
System.out.print(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 TestSynchronization {
public static void main(String
args[]){
Table obj = new Table();
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();
}
}
Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 13
Solution with synchronized method
class Table {
synchronized void printTable(int n) {
for (int i = 1; i <= 5; i++) {
System.out.print(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 TestSynchronization {
public static void main(String
args[]){
Table obj = new Table();
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();
}
}
Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 14
Solution with synchronized blocks
class Table {
void printTable(int n) {
for (int i = 1; i <= 5; i++) {
System.out.print(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() {
synchronized (t) {
t.printTable(5);
}
}
}
class MyThread2 extends
Thread {
Table t;
MyThread1(Table t) {
this.t = t;
}
public void run() {
synchronized (t) {
t.printTable(100);
}
}
}
public class TestSynchronization {
public static void main(String
args[]){
Table obj = new Table();
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();
}
}
Ad

More Related Content

Similar to oops 2 (20)

Concept of Java Multithreading-Partially.pptx
Concept of Java Multithreading-Partially.pptxConcept of Java Multithreading-Partially.pptx
Concept of Java Multithreading-Partially.pptx
SahilKumar542
 
Java Multithreading - how to create threads
Java Multithreading - how to create threadsJava Multithreading - how to create threads
Java Multithreading - how to create threads
ManishKumar475693
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programming
Sonam Sharma
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
PragatiSutar4
 
Thread 1
Thread 1Thread 1
Thread 1
RAVI MAURYA
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
Shipra Swati
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة السابعة
شرح مقرر البرمجة 2   لغة جافا - الوحدة السابعةشرح مقرر البرمجة 2   لغة جافا - الوحدة السابعة
شرح مقرر البرمجة 2 لغة جافا - الوحدة السابعة
جامعة القدس المفتوحة
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
myrajendra
 
Module - 5 merged.docx notes about engineering subjects java
Module - 5 merged.docx notes about engineering subjects javaModule - 5 merged.docx notes about engineering subjects java
Module - 5 merged.docx notes about engineering subjects java
KaviShetty
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming language
arnavytstudio2814
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
HemantSharma134028
 
Lec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreadingLec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreading
kavitamittal18
 
Multi threading
Multi threadingMulti threading
Multi threading
Mavoori Soshmitha
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
Kuntal Bhowmick
 
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbjava.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
jakjak36
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
Kuntal Bhowmick
 
java multi threading and synchronisation.ppt
java multi threading and synchronisation.pptjava multi threading and synchronisation.ppt
java multi threading and synchronisation.ppt
ansariparveen06
 
Multithreading
MultithreadingMultithreading
Multithreading
SanthiNivas
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
Rakesh Madugula
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
AmbigaMurugesan
 
Concept of Java Multithreading-Partially.pptx
Concept of Java Multithreading-Partially.pptxConcept of Java Multithreading-Partially.pptx
Concept of Java Multithreading-Partially.pptx
SahilKumar542
 
Java Multithreading - how to create threads
Java Multithreading - how to create threadsJava Multithreading - how to create threads
Java Multithreading - how to create threads
ManishKumar475693
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programming
Sonam Sharma
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة السابعة
شرح مقرر البرمجة 2   لغة جافا - الوحدة السابعةشرح مقرر البرمجة 2   لغة جافا - الوحدة السابعة
شرح مقرر البرمجة 2 لغة جافا - الوحدة السابعة
جامعة القدس المفتوحة
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
myrajendra
 
Module - 5 merged.docx notes about engineering subjects java
Module - 5 merged.docx notes about engineering subjects javaModule - 5 merged.docx notes about engineering subjects java
Module - 5 merged.docx notes about engineering subjects java
KaviShetty
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming language
arnavytstudio2814
 
Lec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreadingLec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreading
kavitamittal18
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
Kuntal Bhowmick
 
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbjava.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
jakjak36
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
Kuntal Bhowmick
 
java multi threading and synchronisation.ppt
java multi threading and synchronisation.pptjava multi threading and synchronisation.ppt
java multi threading and synchronisation.ppt
ansariparveen06
 

Recently uploaded (20)

five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Journal of Soft Computing in Civil Engineering
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G..."Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...
Infopitaara
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Ad

oops 2

  • 1. Darshan Institute of Engineering & Technology, Rajkot [email protected] 9537133260 Computer Engineering Department Prof. Jayesh D. Vagadiya Object Oriented Programming -I (3140705) Unit-12 Concurrency / Multithreading
  • 2.  Looping Outline Multithreading Life Cycle of Thread Creating a Thread Using Thread Class Using Runnable Interface Join Synchronized
  • 3. Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 3 What is Multithreading?  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.  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.  A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies.  Lets see the life cycle of the thread.
  • 4. Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 4 Life cycle of a Thread  There are 5 stages in the life cycle of the Thread  New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.  Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.  Waiting: Sometimes a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals waiting thread to continue.  Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.  Terminated: A runnable thread enters the new runnable timed waiting waiting terminate d Program starts thread unlock signal signalAll aw ait lock await sleep Interval expires T h r e a d c o m p l e t e s T a s k
  • 5. Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 5 Creating a Thread in Java  There are two ways to create a Thread 1. extending the Thread class 2. implementing the Runnable interface
  • 6. Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 6 1) Extending Thread Class  One way to create a thread is to create a new class that extends Thread, and then to create an instance of that class.  The extending class must override the run( ) method, which is the entry point for the new thread.  It must also call start( ) to begin execution of the new thread. class NewThread extends Thread { NewThread() { super("Demo Thread"); System.out.println("Child thread: " + this); start(); // Start the thread } public void run() { try { for (int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); }} class ExtendThread { public static void main(String args[]) { new NewThread(); // create a new thread try { for (int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } }
  • 7. Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 7 2) Implementing Runnable Interface  To implement thread using Runnable interface, Runnable interface needs to be implemented by the class. class NewThread implements Runnable  Class which implements Runnable interface should override the run() method which containts the logic of the thread. public void run( )  Instance of Thread class is created using following constructor. Thread(Runnable threadOb, String threadName);  Here threadOb is an instance of a class that implements the Runnable interface and the name of the new thread is specified by threadName.  start() method of Thread class will invoke the run() method.
  • 8. Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 8 Example Runnable Interface
  • 9. Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 9 Thread using Executor Framework  Steps to execute thread using Executor Framework are as follows: 1. Create a task (Runnable Object) to execute 2. Create Executor Pool using Executors 3. Pass tasks to Executor Pool 4. Shutdown the Executor Pool
  • 10. Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 10 Example Executable Framework class Task implements Runnable { private String name; public Task(String s) { name = s; } public void run() { try { for (int i = 1; i<=5; i++) { System.out.println(nam e+" - task number - "+i); Thread.sleep(1000); } System.out.println(name+" complete"); } catch(InterruptedException e) { e.printStackTrace(); } } } import java.util.concurrent.*; public class ExecutorThreadDemo { public static void main(String[] args) { Runnable r1 = new Task("task 1"); Runnable r2 = new Task("task 2"); Runnable r3 = new Task("task 3"); Runnable r4 = new Task("task 4"); Runnable r5 = new Task("task 5"); ExecutorService pool = Executors.newFixedThreadPool(3) ; pool.execute(r1); pool.execute(r2); pool.execute(r3); pool.execute(r4); pool.execute(r5); pool.shutdown(); } }
  • 11. Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 11 Thread Synchronization  When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issues.  For example, if multiple threads try to write within a same file then they may corrupt the data because one of the threads can override data or while one thread is opening the same file at the same time another thread might be closing the same file.  So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time.  Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized methods & synchronized blocks.
  • 12. Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 12 Problem without synchronization (Example) class Table { void printTable(int n) { for (int i = 1; i <= 5; i++) { System.out.print(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 TestSynchronization { public static void main(String args[]){ Table obj = new Table(); MyThread1 t1 = new MyThread1(obj); MyThread2 t2 = new MyThread2(obj); t1.start(); t2.start(); } }
  • 13. Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 13 Solution with synchronized method class Table { synchronized void printTable(int n) { for (int i = 1; i <= 5; i++) { System.out.print(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 TestSynchronization { public static void main(String args[]){ Table obj = new Table(); MyThread1 t1 = new MyThread1(obj); MyThread2 t2 = new MyThread2(obj); t1.start(); t2.start(); } }
  • 14. Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 14 Solution with synchronized blocks class Table { void printTable(int n) { for (int i = 1; i <= 5; i++) { System.out.print(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() { synchronized (t) { t.printTable(5); } } } class MyThread2 extends Thread { Table t; MyThread1(Table t) { this.t = t; } public void run() { synchronized (t) { t.printTable(100); } } } public class TestSynchronization { public static void main(String args[]){ Table obj = new Table(); MyThread1 t1 = new MyThread1(obj); MyThread2 t2 = new MyThread2(obj); t1.start(); t2.start(); } }