SlideShare a Scribd company logo
GUIDED BY: 
Multithreaded Programming in JAVA 
DEVELOPED BY: Prof. Miral Patel 
Vikram Kalyani 120110116017
What is Multithreading? 
 A multi-processing Operating System can run several processes at the same time 
 Each process has its own address/memory space 
 The OS's scheduler decides when each process is executed 
 Only one process is actually executing at any given time. However, 
the system appears to be running several programs simultaneously 
 Separate processes to not have access to each other's memory space 
 Many OSes have a shared memory system so that processes can 
share memory space 
 In a multithreaded application, there are several points of execution within the 
same memory space. 
 Each point of execution is called a thread 
 Threads share access to memory
Why to use Multithreading? 
 In a single threaded application, one thread of execution must do everything 
 If an application has several tasks to perform, those tasks will be 
performed when the thread can get to them. 
 A single task which requires a lot of processing can make the entire 
application appear to be "sluggish" or unresponsive. 
 In a multithreaded application, each task can be performed by a separate thread 
 If one thread is executing a long process, it does not make the entire 
application wait for it to finish. 
 If a multithreaded application is being executed on a system that has multiple 
processors, the OS may execute separate threads simultaneously on separate 
processors.
What Kind of Applications Use Multithreading? 
 Any kind of application which has distinct tasks which can be performed independently 
 Any application with a GUI. 
 Threads dedicated to the GUI can delegate the processing of user 
requests to other threads. 
 The GUI remains responsive to the user even when the user's requests 
are being processed. 
 Any application which requires asynchronous response 
 Network based applications are ideally suited to multithreading. 
Data can arrive from the network at any time. 
In a single threaded system, data is queued until the thread can 
read the data 
In a multithreaded system, a thread can be dedicated to listening 
for data on the network port 
When data arrives, the thread reads it immediately and processes 
it or delegates its processing to another thread
What are Threads? 
 A piece of code that run in concurrent with other threads. 
 Each thread is a statically ordered sequence of instructions. 
 Threads are being extensively used express concurrency on both single and 
multiprocessors machines. 
 Programming a task having multiple threads of control – Multithreading or 
Multithreaded Programming.
Thread States 
Threads can be in one of four states 
Created, Running, Blocked, and Dead 
A thread's state changes based on: 
Control methods such as start, sleep, yield, wait, notify 
Termination of the run method 
notify() 
Created Runnable Blocked 
Dead 
Thread() start() 
run() method terminates 
sleep() 
wait()
Java Threads 
 Java has built in thread support for Multithreading 
 Synchronization 
 Thread Scheduling 
 Inter-Thread Communication: 
 Java Garbage Collector is a low-priority thread
Threading Mechanisms 
 Create a class that extends the Thread class 
 Create a class that implements the Runnable interface
1st Method 
Extending Thread class 
 Threads are implemented as objects that contains a method called 
run() 
class MyThread extends Thread 
{ 
public void run() 
{ 
// thread body of execution 
} 
} 
 Create a thread: 
MyThread thr1 = new MyThread(); 
 Start Execution of threads: 
thr1.start();
An example 
class MyThread extends Thread { // the thread 
public void run() { 
System.out.println(" this thread is running ... "); 
} 
} // end class MyThread 
class ThreadEx1 { // a program that utilizes the thread 
public static void main(String [] args ) { 
MyThread t = new MyThread(); 
// due to extending the Thread class (above) 
// I can call start(), and this will call 
// run(). start() is a method in class Thread. 
t.start(); 
} // end main() 
} // end class ThreadEx1
2nd Method 
Threads by implementing Runnable interface 
class MyThread implements Runnable 
{ 
..... 
public void run() 
{ 
// thread body of execution 
} 
} 
 Creating Object: 
MyThread myObject = new MyThread(); 
 Creating Thread Object: 
Thread thr1 = new Thread( myObject ); 
 Start Execution: 
thr1.start();
An example 
class MyThread implements Runnable { 
public void run() { 
System.out.println(" this thread is running ... "); 
} 
} // end class MyThread 
class ThreadEx2 { 
public static void main(String [] args ) { 
Thread t = new Thread(new MyThread()); 
// due to implementing the Runnable interface 
// We can call start(), and this will call run(). 
t.start(); 
} // end main() 
} // end class ThreadEx2
Thread Priority 
 In Java, each thread is assigned priority, which affects the 
order in which it is scheduled for running. The threads so far had 
same default priority (ORM_PRIORITY) and they are served using 
FCFS policy. 
 Java allows users to change priority: 
ThreadName.setPriority(intNumber) 
MIN_PRIORITY = 1 
NORM_PRIORITY=5 
MAX_PRIORITY=10
Thread priority Example 
class A extends Thread 
{ 
public void run() 
{ 
System.out.println("Thread A 
started"); 
for(int i=1;i<=4;i++) 
{ 
System.out.println("t From 
ThreadA: i= "+i); 
} 
System.out.println("Exit from A"); 
} 
} 
class B extends Thread 
{ 
public void run() 
{ 
System.out.println("Thread B 
started"); 
for(int j=1;j<=4;j++) 
{ 
System.out.println("t From 
ThreadB: j= "+j); 
} 
System.out.println("Exit from B"); 
} 
}
Thread priority Example(Cont.) 
class C extends Thread 
{ 
public void run() 
{ 
System.out.println("Thread C started"); 
for(int k=1;k<=4;k++) 
{ 
System.out.println("t From ThreadC: k= "+k); 
} 
System.out.println("Exit from C"); 
} 
}
Thread priority Example(Cont.) 
class ThreadPriority 
{ 
public static void main(String args[]) 
{ 
A threadA=new A(); 
B threadB=new B(); 
C threadC=new C(); 
threadC.setPriority(Thread.MAX_PRIORITY); 
threadB.setPriority(threadA.getPriority()+1); 
threadA.setPriority(Thread.MIN_PRIORITY); 
System.out.println("Started Thread A"); 
threadA.start(); 
System.out.println("Started Thread B"); 
threadB.start(); 
System.out.println("Started Thread C"); 
threadC.start(); 
System.out.println("End of main thread"); 
} 
}
Deadlock: What is it ? 
 A special type of error which occurs when two threads have 
a circular dependency on a pair of synchronized objects. 
 For example, Traffic Jam. 
 Device allocation 
 Thread 1 requests tape drive 1 & gets it. 
 Thread 2 requests tape drive 2 & gets it. 
 Thread 1 requests tape drive 2 but is blocked. 
 Thread 2 requests tape drive 1 but is blocked.
Deadlock as error: 
 Deadlock is a difficult error to debug for two reasons.. 
In general, it occurs only rarely, when the two threads 
time-slice in just the right way. 
It may involve more than two threads and two 
synchronized objects.
Suspending, Resuming, and Stopping Threads 
 Sometimes, suspending execution of a thread is useful as a 
solution of deadlock. 
 The methods are…. 
void suspend( ) 
void resume( ) 
Void stop()
Java Synchonization 
 Java provides Synchronized keyword to methods that cause only one invocation of a synchronized 
method on the same object at a time. 
Example 
public class SynchronizedCounter { 
private int c = 0; 
public synchronized void increment() { 
c++; 
} 
public synchronized void decrement() { 
c--; 
} 
public synchronized int value() { 
return c; 
} 
}
21 
Synchronized Statements 
Unlike synchronized methods, synchronized 
statements must specify the object that provides the 
intrinsic lock: 
Uses construct ion: 
synchronized ( expression ) { 
statements 
} 
Evaluate to an 
object or an 
array. Used to 
identify lock. 
“critical section”
22 
Synchronized Statements 
Example: 
public void addName(String name) { 
synchronized(this) { 
lastName = name; 
nameCount++; 
} 
nameList.add(name); 
} 
Only this part 
synchronized
Atomic action 
An atomic action cannot stop in the middle: it either happens completely, or it 
doesn't happen at all. No side effects of an atomic action are visible until the 
action is complete. 
Read/writes can be declared atomic with the volatile keyword, e.g. 
private volatile int x; 
Sometimes can be more efficient than synchronized methods
Coordinating threads 
Wait/notify mechanism 
 Sometimes need a thread to stop running and wait for an event before continuing. 
 wait() and notify() methods are methods of class Object. 
 Every object can maintain a list of waiting threads. 
wait(): When a thread calls wait() method of an object, any locks the thread 
holds are temporarily released and thread added to list of waiting threads for that 
object and stops running. 
notify(): When another thread calls notify() method on the same object, object 
wakes up one of the waiting threads and allows it to continue.
Join 
 Sometimes one thread needs to stop and wait for another thread to 
complete. 
 join() -- waits for a thread to die, i.e. thr1.join() waits for thread thr1 to die. 
 Calling return() from the run method implicitly causes the thread to exit.
Multi-threaded Programming in JAVA

More Related Content

What's hot (20)

MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
OOPS In JAVA.pptx
OOPS In JAVA.pptxOOPS In JAVA.pptx
OOPS In JAVA.pptx
Sachin33417
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
VINOTH R
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
Lovely Professional University
 
Method overloading
Method overloadingMethod overloading
Method overloading
Lovely Professional University
 
Java Networking
Java NetworkingJava Networking
Java Networking
Sunil OS
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
Lovely Professional University
 
Super Keyword in Java.pptx
Super Keyword in Java.pptxSuper Keyword in Java.pptx
Super Keyword in Java.pptx
KrutikaWankhade1
 
Java awt
Java awtJava awt
Java awt
Arati Gadgil
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
shanmuga rajan
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
parag
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
Java package
Java packageJava package
Java package
CS_GDRCST
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
lalithambiga kamaraj
 
Java Collections
Java  Collections Java  Collections
Java Collections
Kongu Engineering College, Perundurai, Erode
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
Applets in java
Applets in javaApplets in java
Applets in java
Wani Zahoor
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
Nahian Ahmed
 
Applets
AppletsApplets
Applets
Prabhakaran V M
 

Viewers also liked (20)

Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
Arun Mehra
 
Java Swing
Java SwingJava Swing
Java Swing
Shraddha
 
Operating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingOperating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programming
guesta40f80
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Java applets
Java appletsJava applets
Java applets
Srinath Dhayalamoorthy
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
vanithaRamasamy
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
Ganesh Samarthyam
 
Interfaces c#
Interfaces c#Interfaces c#
Interfaces c#
Nipam Medhi
 
interface in c#
interface in c#interface in c#
interface in c#
Deepti Pillai
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
myrajendra
 
Java swing 1
Java swing 1Java swing 1
Java swing 1
Mukesh Tekwani
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in Java
CIB Egypt
 
My History
My HistoryMy History
My History
santosh mishra
 
IO In Java
IO In JavaIO In Java
IO In Java
parag
 
java programming- control statements
 java programming- control statements java programming- control statements
java programming- control statements
jyoti_lakhani
 
Design Pattern From Java To Ruby
Design Pattern From Java To RubyDesign Pattern From Java To Ruby
Design Pattern From Java To Ruby
yelogic
 
Thread presentation
Thread presentationThread presentation
Thread presentation
AAshish Ojha
 
5.interface and packages
5.interface and packages5.interface and packages
5.interface and packages
Deepak Sharma
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
Arun Mehra
 
Java Swing
Java SwingJava Swing
Java Swing
Shraddha
 
Operating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programmingOperating System Chapter 4 Multithreaded programming
Operating System Chapter 4 Multithreaded programming
guesta40f80
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
myrajendra
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in Java
CIB Egypt
 
IO In Java
IO In JavaIO In Java
IO In Java
parag
 
java programming- control statements
 java programming- control statements java programming- control statements
java programming- control statements
jyoti_lakhani
 
Design Pattern From Java To Ruby
Design Pattern From Java To RubyDesign Pattern From Java To Ruby
Design Pattern From Java To Ruby
yelogic
 
Thread presentation
Thread presentationThread presentation
Thread presentation
AAshish Ojha
 
5.interface and packages
5.interface and packages5.interface and packages
5.interface and packages
Deepak Sharma
 
Ad

Similar to Multi-threaded Programming in JAVA (20)

Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
raksharao
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
mha4
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
mha4
 
MSBTE Computer Engineering JPR java. multi. threading.pptx
MSBTE Computer Engineering  JPR java.  multi. threading.pptxMSBTE Computer Engineering  JPR java.  multi. threading.pptx
MSBTE Computer Engineering JPR java. multi. threading.pptx
kunalgaikwad1705
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Threads
ThreadsThreads
Threads
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH, SINDH, PAKISTAN
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
ssusere538f7
 
Multi t hreading_14_10
Multi t hreading_14_10Multi t hreading_14_10
Multi t hreading_14_10
Minal Maniar
 
Thread priorities in java
Thread priorities in javaThread priorities in java
Thread priorities in java
Ducat India
 
java multi threading and synchronisation.ppt
java multi threading and synchronisation.pptjava multi threading and synchronisation.ppt
java multi threading and synchronisation.ppt
ansariparveen06
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
HarshaDokula
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
Rajkattamuri
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
Mohammed625
 
multithreading,thread and processinjava-210302183809.pptx
multithreading,thread and processinjava-210302183809.pptxmultithreading,thread and processinjava-210302183809.pptx
multithreading,thread and processinjava-210302183809.pptx
ArunPatrick2
 
Threads in java
Threads in javaThreads in java
Threads in java
mukesh singh
 
Programming - Java-Threads-and-Synchronization.ppt
Programming - Java-Threads-and-Synchronization.pptProgramming - Java-Threads-and-Synchronization.ppt
Programming - Java-Threads-and-Synchronization.ppt
smychung
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Multi Threading
Multi ThreadingMulti Threading
Multi Threading
Ferdin Joe John Joseph PhD
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
junnubabu
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
raksharao
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
mha4
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
mha4
 
MSBTE Computer Engineering JPR java. multi. threading.pptx
MSBTE Computer Engineering  JPR java.  multi. threading.pptxMSBTE Computer Engineering  JPR java.  multi. threading.pptx
MSBTE Computer Engineering JPR java. multi. threading.pptx
kunalgaikwad1705
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
ssusere538f7
 
Multi t hreading_14_10
Multi t hreading_14_10Multi t hreading_14_10
Multi t hreading_14_10
Minal Maniar
 
Thread priorities in java
Thread priorities in javaThread priorities in java
Thread priorities in java
Ducat India
 
java multi threading and synchronisation.ppt
java multi threading and synchronisation.pptjava multi threading and synchronisation.ppt
java multi threading and synchronisation.ppt
ansariparveen06
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
Rajkattamuri
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
Mohammed625
 
multithreading,thread and processinjava-210302183809.pptx
multithreading,thread and processinjava-210302183809.pptxmultithreading,thread and processinjava-210302183809.pptx
multithreading,thread and processinjava-210302183809.pptx
ArunPatrick2
 
Programming - Java-Threads-and-Synchronization.ppt
Programming - Java-Threads-and-Synchronization.pptProgramming - Java-Threads-and-Synchronization.ppt
Programming - Java-Threads-and-Synchronization.ppt
smychung
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
junnubabu
 
Ad

More from Vikram Kalyani (6)

Manganese - Alloy
Manganese - AlloyManganese - Alloy
Manganese - Alloy
Vikram Kalyani
 
Marketing on the web
Marketing on the webMarketing on the web
Marketing on the web
Vikram Kalyani
 
Windows_App_Development_Workshop
Windows_App_Development_WorkshopWindows_App_Development_Workshop
Windows_App_Development_Workshop
Vikram Kalyani
 
Human Resource Management
Human Resource ManagementHuman Resource Management
Human Resource Management
Vikram Kalyani
 
Technology in education
Technology in educationTechnology in education
Technology in education
Vikram Kalyani
 
Presentation Techniques
Presentation TechniquesPresentation Techniques
Presentation Techniques
Vikram Kalyani
 
Windows_App_Development_Workshop
Windows_App_Development_WorkshopWindows_App_Development_Workshop
Windows_App_Development_Workshop
Vikram Kalyani
 
Human Resource Management
Human Resource ManagementHuman Resource Management
Human Resource Management
Vikram Kalyani
 
Technology in education
Technology in educationTechnology in education
Technology in education
Vikram Kalyani
 
Presentation Techniques
Presentation TechniquesPresentation Techniques
Presentation Techniques
Vikram Kalyani
 

Recently uploaded (20)

社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
ijfcstjournal
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
Introduction to AI agent development with MCP
Introduction to AI agent development with MCPIntroduction to AI agent development with MCP
Introduction to AI agent development with MCP
Dori Waldman
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptxWeek 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptxDevelopment of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair KitSEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 
IntroSlides-June-GDG-Cloud-Munich community [email protected]
IntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdfIntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdf
IntroSlides-June-GDG-Cloud-Munich community [email protected]
Luiz Carneiro
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdfHow Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
Journal of Soft Computing in Civil Engineering
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
ijfcstjournal
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
Introduction to AI agent development with MCP
Introduction to AI agent development with MCPIntroduction to AI agent development with MCP
Introduction to AI agent development with MCP
Dori Waldman
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptxWeek 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptxDevelopment of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair KitSEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdfHow Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 

Multi-threaded Programming in JAVA

  • 1. GUIDED BY: Multithreaded Programming in JAVA DEVELOPED BY: Prof. Miral Patel Vikram Kalyani 120110116017
  • 2. What is Multithreading?  A multi-processing Operating System can run several processes at the same time  Each process has its own address/memory space  The OS's scheduler decides when each process is executed  Only one process is actually executing at any given time. However, the system appears to be running several programs simultaneously  Separate processes to not have access to each other's memory space  Many OSes have a shared memory system so that processes can share memory space  In a multithreaded application, there are several points of execution within the same memory space.  Each point of execution is called a thread  Threads share access to memory
  • 3. Why to use Multithreading?  In a single threaded application, one thread of execution must do everything  If an application has several tasks to perform, those tasks will be performed when the thread can get to them.  A single task which requires a lot of processing can make the entire application appear to be "sluggish" or unresponsive.  In a multithreaded application, each task can be performed by a separate thread  If one thread is executing a long process, it does not make the entire application wait for it to finish.  If a multithreaded application is being executed on a system that has multiple processors, the OS may execute separate threads simultaneously on separate processors.
  • 4. What Kind of Applications Use Multithreading?  Any kind of application which has distinct tasks which can be performed independently  Any application with a GUI.  Threads dedicated to the GUI can delegate the processing of user requests to other threads.  The GUI remains responsive to the user even when the user's requests are being processed.  Any application which requires asynchronous response  Network based applications are ideally suited to multithreading. Data can arrive from the network at any time. In a single threaded system, data is queued until the thread can read the data In a multithreaded system, a thread can be dedicated to listening for data on the network port When data arrives, the thread reads it immediately and processes it or delegates its processing to another thread
  • 5. What are Threads?  A piece of code that run in concurrent with other threads.  Each thread is a statically ordered sequence of instructions.  Threads are being extensively used express concurrency on both single and multiprocessors machines.  Programming a task having multiple threads of control – Multithreading or Multithreaded Programming.
  • 6. Thread States Threads can be in one of four states Created, Running, Blocked, and Dead A thread's state changes based on: Control methods such as start, sleep, yield, wait, notify Termination of the run method notify() Created Runnable Blocked Dead Thread() start() run() method terminates sleep() wait()
  • 7. Java Threads  Java has built in thread support for Multithreading  Synchronization  Thread Scheduling  Inter-Thread Communication:  Java Garbage Collector is a low-priority thread
  • 8. Threading Mechanisms  Create a class that extends the Thread class  Create a class that implements the Runnable interface
  • 9. 1st Method Extending Thread class  Threads are implemented as objects that contains a method called run() class MyThread extends Thread { public void run() { // thread body of execution } }  Create a thread: MyThread thr1 = new MyThread();  Start Execution of threads: thr1.start();
  • 10. An example class MyThread extends Thread { // the thread public void run() { System.out.println(" this thread is running ... "); } } // end class MyThread class ThreadEx1 { // a program that utilizes the thread public static void main(String [] args ) { MyThread t = new MyThread(); // due to extending the Thread class (above) // I can call start(), and this will call // run(). start() is a method in class Thread. t.start(); } // end main() } // end class ThreadEx1
  • 11. 2nd Method Threads by implementing Runnable interface class MyThread implements Runnable { ..... public void run() { // thread body of execution } }  Creating Object: MyThread myObject = new MyThread();  Creating Thread Object: Thread thr1 = new Thread( myObject );  Start Execution: thr1.start();
  • 12. An example class MyThread implements Runnable { public void run() { System.out.println(" this thread is running ... "); } } // end class MyThread class ThreadEx2 { public static void main(String [] args ) { Thread t = new Thread(new MyThread()); // due to implementing the Runnable interface // We can call start(), and this will call run(). t.start(); } // end main() } // end class ThreadEx2
  • 13. Thread Priority  In Java, each thread is assigned priority, which affects the order in which it is scheduled for running. The threads so far had same default priority (ORM_PRIORITY) and they are served using FCFS policy.  Java allows users to change priority: ThreadName.setPriority(intNumber) MIN_PRIORITY = 1 NORM_PRIORITY=5 MAX_PRIORITY=10
  • 14. Thread priority Example class A extends Thread { public void run() { System.out.println("Thread A started"); for(int i=1;i<=4;i++) { System.out.println("t From ThreadA: i= "+i); } System.out.println("Exit from A"); } } class B extends Thread { public void run() { System.out.println("Thread B started"); for(int j=1;j<=4;j++) { System.out.println("t From ThreadB: j= "+j); } System.out.println("Exit from B"); } }
  • 15. Thread priority Example(Cont.) class C extends Thread { public void run() { System.out.println("Thread C started"); for(int k=1;k<=4;k++) { System.out.println("t From ThreadC: k= "+k); } System.out.println("Exit from C"); } }
  • 16. Thread priority Example(Cont.) class ThreadPriority { public static void main(String args[]) { A threadA=new A(); B threadB=new B(); C threadC=new C(); threadC.setPriority(Thread.MAX_PRIORITY); threadB.setPriority(threadA.getPriority()+1); threadA.setPriority(Thread.MIN_PRIORITY); System.out.println("Started Thread A"); threadA.start(); System.out.println("Started Thread B"); threadB.start(); System.out.println("Started Thread C"); threadC.start(); System.out.println("End of main thread"); } }
  • 17. Deadlock: What is it ?  A special type of error which occurs when two threads have a circular dependency on a pair of synchronized objects.  For example, Traffic Jam.  Device allocation  Thread 1 requests tape drive 1 & gets it.  Thread 2 requests tape drive 2 & gets it.  Thread 1 requests tape drive 2 but is blocked.  Thread 2 requests tape drive 1 but is blocked.
  • 18. Deadlock as error:  Deadlock is a difficult error to debug for two reasons.. In general, it occurs only rarely, when the two threads time-slice in just the right way. It may involve more than two threads and two synchronized objects.
  • 19. Suspending, Resuming, and Stopping Threads  Sometimes, suspending execution of a thread is useful as a solution of deadlock.  The methods are…. void suspend( ) void resume( ) Void stop()
  • 20. Java Synchonization  Java provides Synchronized keyword to methods that cause only one invocation of a synchronized method on the same object at a time. Example public class SynchronizedCounter { private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; } public synchronized int value() { return c; } }
  • 21. 21 Synchronized Statements Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock: Uses construct ion: synchronized ( expression ) { statements } Evaluate to an object or an array. Used to identify lock. “critical section”
  • 22. 22 Synchronized Statements Example: public void addName(String name) { synchronized(this) { lastName = name; nameCount++; } nameList.add(name); } Only this part synchronized
  • 23. Atomic action An atomic action cannot stop in the middle: it either happens completely, or it doesn't happen at all. No side effects of an atomic action are visible until the action is complete. Read/writes can be declared atomic with the volatile keyword, e.g. private volatile int x; Sometimes can be more efficient than synchronized methods
  • 24. Coordinating threads Wait/notify mechanism  Sometimes need a thread to stop running and wait for an event before continuing.  wait() and notify() methods are methods of class Object.  Every object can maintain a list of waiting threads. wait(): When a thread calls wait() method of an object, any locks the thread holds are temporarily released and thread added to list of waiting threads for that object and stops running. notify(): When another thread calls notify() method on the same object, object wakes up one of the waiting threads and allows it to continue.
  • 25. Join  Sometimes one thread needs to stop and wait for another thread to complete.  join() -- waits for a thread to die, i.e. thr1.join() waits for thread thr1 to die.  Calling return() from the run method implicitly causes the thread to exit.