SlideShare a Scribd company logo
*
2
*
3
*
*Thread: single sequential flow of control within
a program
*Single-threaded program can handle one task
at any time.
*Multitasking allows single processor to run
several concurrent threads.
*Most modern operating systems support
multitasking.
4
*
*Reactive systems – constantly monitoring
*More responsive to user input – GUI application can
interrupt a time-consuming task
*Server can handle multiple clients simultaneously
*Can take advantage of parallel processing
*Different processes do not share memory space.
*A thread can execute concurrently with other threads
within a single process.
*All threads managed by the JVM share memory space and
can communicate with each other.
5
*
Multiple
threads
on
multiple
CPUs
Multiple
threads
sharing a
single CPU
Thread 3
Thread 2
Thread 1
Thread 3
Thread 2
Thread 1
6
*
Creating threads in Java:
*Extend java.lang.Thread
OR
*Implement java.lang.Runnable
7
*
Creating threads in Java:
*Extend java.lang.Thread class
*run() method must be overridden (similar to main method of
sequential program)
*run() is called when execution of the thread begins
*A thread terminates when run() returns
*start() method invokes run()
*Calling run() does not create a new thread
*Implement java.lang.Runnable interface
*If already inheriting another class (i.e., JApplet)
*Single method: public void run()
*Thread class implements Runnable.
8
*
9
*
A thread becomes Not Runnable when one of
these events occurs:
* Its sleep method is invoked.
* The thread calls the wait method to wait for a
specific condition to be satisfied.
* The thread is blocked by I/O.
10
*
java.lang.Thread
+Thread()
+Thread(task: Runnable)
+start(): void
+isAlive(): boolean
+setPriority(p: int): void
+join(): void
+sleep(millis: long): void
+yield(): void
+interrupt(): void
Creates a default thread.
Creates a thread for a specified task.
Starts the thread that causes the run() method to be invoked by the JVM.
Tests whether the thread is currently running.
Sets priority p (ranging from 1 to 10) for this thread.
Waits for this thread to finish.
Puts the runnable object to sleep for a specified time in milliseconds.
Causes this thread to temporarily pause and allow other threads to execute.
Interrupts this thread.
«interface»
java.lang.Runnable
Method Meaning
*getName Obtain a thread’s name.
*getPriority Obtain a thread’s priority.
*isAlive Determine if a thread is still
running.
*join Wait for a thread to terminate.
*run Entry point for the thread.
*sleep Suspend a thread for a period of
time.
*Start Start a thread by calling its run
method.
The Main Thread
When a Java program starts up, one thread begins running
immediately. This is usually called the main thread of your
program, because it is the one that is executed when your
program begins.
The main thread is important for two reasons:
 It is the thread from which other “child” threads will be
spawned.
 Often, it must be the last thread to finish execution
because it performs various shutdown actions.
Although the main thread is created automatically when your
program is started, it can be controlled through a Thread
object. This can be done by calling the method
currentThread( ), which is a public static member of
Thread. Its general form is
static Thread currentThread( )
This method returns a reference to the thread in which it is
called.
13
*
class CurrentThreadDemo {
public static void main(String args[]) {
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
// change the name of the thread
t.setName("My Thread");
System.out.println("After name change: " + t);
try {
for(int n = 5; n > 0; n--) {
System.out.println(n);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}}}
*
Current thread: Thread[main,5,main]
After name change: Thread[My Thread,5,main]
5
4
3
2
1
15
*
New Ready
Thread created
Finished
Running
start()
run()
Wait fortarget
tofinish
join()
run()returns
yield(), or
timeout
interrupt()
Wait fortime
out
Wait tobe
notified
sleep()
wait()
Target
finished
notify()or
notifyAll()
Timeout
Blocked
Interrupted()
A thread can be in one of five states: New, Ready, Running, Blocked, or Finished.
16
*
You can use the yield() method to temporarily release time for
other threads.
public void run() {
for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
Thread.yield();
}
}
Every time a number is printed, the print100 thread is yielded. So,
the numbers are printed after the characters.
17
*
The sleep(long mills) method puts the thread to sleep
for the specified time in milliseconds.
public void run() {
for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
try {
if (i >= 50) Thread.sleep(1);
}
catch (InterruptedException ex) {
}
}
}
Every time a number (>= 50) is printed, the print100
thread is put to sleep for 1 millisecond.
18
*
You can use the join() method to force one thread to
wait for another thread to finish.
The numbers after 50 are printed after thread printA is finished.
printA.join()
-char token
+getToken
+setToken
+paintCompone
t
+mouseClicked
Thread
print100
-char token
+getToken
+setToken
+paintCompo
net
+mouseClicke
d
Wait for printA
to finish
+getToken
+setToken
+paintComponet
Thread
printA
-char token
+getToken
+setToken
+paintCompo
net
+mouseClicke
d
printA finished
-char token
public void run() {
Thread thread4 = new Thread(
new PrintChar('c', 40));
thread4.start();
try {
for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
if (i == 50) thread4.join();
}
}
catch (InterruptedException ex) {
}
}
19
*
isAlive()
• method used to find out the state of a thread.
• returns true: thread is in the Ready, Blocked, or
Running state
• returns false: thread is new and has not started or if it
is finished.
interrupt()
f a thread is currently in the Ready or Running state, its
interrupted flag is set; if a thread is currently blocked,
it is awakened and enters the Ready state, and an
java.io.InterruptedException is thrown.
The isInterrupt() method tests whether the thread is
interrupted.
20
*
NOTE: The Thread class also contains the stop(), suspend(),
and resume() methods. As of Java 2, these methods are
deprecated (or outdated) because they are known to be
inherently unsafe. You should assign null to a Thread variable
to indicate that it is stopped rather than use the stop()
method.
21
*
// Create a second thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500) ;} }
22
catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}}
class ThreadDemo {
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.");
} }
23
*
• Each thread is assigned a default priority of
Thread.NORM_PRIORITY (constant of 5). You
can reset the priority using setPriority(int
priority).
• Some constants for priorities include
Thread.MIN_PRIORITY
Thread.MAX_PRIORITY
Thread.NORM_PRIORITY
• By default, a thread has the priority level of the
thread that created it.
24
// Demonstrate thread priorities.
class clicker implements Runnable {
long click = 0;
Thread t;
private volatile boolean running = true;
public clicker(int p) {
t = new Thread(this);
t.setPriority(p);
}
public void run() {
while (running) {
click++;
} }
public void stop() {
running = false;
}
public void start() {
t.start(); } }
25
class HiLoPri {
public static void main(String args[]) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY - 2);
lo.start();
hi.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
lo.stop();
hi.stop();
26
// Wait for child threads to terminate.
try {
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread: " + lo.click);
System.out.println("High-priority thread: " + hi.click);
}
}
o/p :
Low-priority thread: 4408112
High-priority thread: 589626904
27
*
class NewThread implements Runnable
{
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name +"Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThreadDemo {
public static void main(String args[]) {
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try {
// wait for other threads to end
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}System.out.println("Main thread exiting.");
}}
*
*Synchronization is prevent data corruption
*Synchronization allows only one thread to
perform an operation on a object at a time.
*If multiple threads require an access to an
object, synchronization helps in maintaining
consistency.
*A shared resource may be corrupted if it is
accessed simultaneously by multiple threads.
*
public class Counter{
private int count = 0;
public int getCount(){
return count;
}
public setCount(int count){
this.count = count;
}
}
*In this example, the counter tells how many access has been made.
*If a thread is accessing setCount and updating count and another
thread is accessing getCount at the same time, there will be
inconsistency in the value of count.
*
public class Counter{
private static int count = 0;
public synchronized int getCount(){
return count;
}
public synchoronized setCount(int count){
this.count = count;
}
}
*By adding the synchronized keyword we make sure that when one thread is in
the setCount method the other threads are all in waiting state.
*The synchronized keyword places a lock on the object, and hence locks all the
other methods which have the keyword synchronized. The lock does not lock
the methods without the keyword synchronized and hence they are open to
access by other threads.
31
*
•Conditions can be used for communication among threads.
•A thread can specify what to do under a certain condition.
•newCondition() method of Lock object.
•Condition methods:
•await() current thread waits until the condition is signaled
•signal() wakes up a waiting thread
•signalAll() wakes all waiting threads
«interface»
java.util.concurrent.Condition
+await(): void
+signal(): void
+signalAll(): Condition
Causes the current thread to
wait until the condition is
signaled.
Wakes up one waiting
thread.
Wakes up all waiting threads.
32
*
Use the wait(), notify(), and notifyAll() methods to facilitate
communication among threads.
The wait(), notify(), and notifyAll() methods must be called in
a synchronized method or a synchronized block on the calling
object of these methods. Otherwise, an
IllegalMonitorStateException would occur.
The wait() method lets the thread wait until some condition
occurs. When it occurs, you can use the notify() or notifyAll()
methods to notify the waiting threads to resume normal
execution. The notifyAll() method wakes up all waiting
threads, while notify() picks up only one thread from a
waiting queue.

More Related Content

Similar to Java Multithreading.pptx

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Arafat Hossan
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
PragatiSutar4
 
Multi threading
Multi threadingMulti threading
Multi threading
Mavoori Soshmitha
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
creativegamerz00
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
TabassumMaktum
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
TabassumMaktum
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
kashyapneha2809
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
nehakumari0xf
 
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
 
chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)
It Academy
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
04 threads
04 threads04 threads
04 threads
ambar khetan
 
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
 
Multi threading
Multi threadingMulti threading
Multi threading
PavanAnudeepMotiki
 
JAVA THREADS.pdf
JAVA THREADS.pdfJAVA THREADS.pdf
JAVA THREADS.pdf
Mohit Kumar
 
Threads in java
Threads in javaThreads in java
Threads in java
mukesh singh
 

Similar to Java Multithreading.pptx (20)

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Multi threading
Multi threadingMulti threading
Multi threading
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
04 threads
04 threads04 threads
04 threads
 
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
 
Multi threading
Multi threadingMulti threading
Multi threading
 
JAVA THREADS.pdf
JAVA THREADS.pdfJAVA THREADS.pdf
JAVA THREADS.pdf
 
Threads in java
Threads in javaThreads in java
Threads in java
 

More from RanjithaM32

svm.ppt
svm.pptsvm.ppt
svm.ppt
RanjithaM32
 
Various types of File Operations in Java
Various types of  File Operations in JavaVarious types of  File Operations in Java
Various types of File Operations in Java
RanjithaM32
 
Unit 4 Ethics in health research.pptx
Unit 4 Ethics in health research.pptxUnit 4 Ethics in health research.pptx
Unit 4 Ethics in health research.pptx
RanjithaM32
 
Unit 1 NoSQL commands.pptx
Unit 1 NoSQL commands.pptxUnit 1 NoSQL commands.pptx
Unit 1 NoSQL commands.pptx
RanjithaM32
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
RanjithaM32
 
ARtificial Intelligence Knowledge Representation.pptx
ARtificial Intelligence Knowledge Representation.pptxARtificial Intelligence Knowledge Representation.pptx
ARtificial Intelligence Knowledge Representation.pptx
RanjithaM32
 
Lisp.pptx
Lisp.pptxLisp.pptx
Lisp.pptx
RanjithaM32
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
RanjithaM32
 
Html introduction
Html introductionHtml introduction
Html introduction
RanjithaM32
 
Threads
ThreadsThreads
Threads
RanjithaM32
 
Types of learning
Types of learningTypes of learning
Types of learning
RanjithaM32
 
Ml introduction
Ml introductionMl introduction
Ml introduction
RanjithaM32
 
Knowledge base system
Knowledge base systemKnowledge base system
Knowledge base system
RanjithaM32
 

More from RanjithaM32 (13)

svm.ppt
svm.pptsvm.ppt
svm.ppt
 
Various types of File Operations in Java
Various types of  File Operations in JavaVarious types of  File Operations in Java
Various types of File Operations in Java
 
Unit 4 Ethics in health research.pptx
Unit 4 Ethics in health research.pptxUnit 4 Ethics in health research.pptx
Unit 4 Ethics in health research.pptx
 
Unit 1 NoSQL commands.pptx
Unit 1 NoSQL commands.pptxUnit 1 NoSQL commands.pptx
Unit 1 NoSQL commands.pptx
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
 
ARtificial Intelligence Knowledge Representation.pptx
ARtificial Intelligence Knowledge Representation.pptxARtificial Intelligence Knowledge Representation.pptx
ARtificial Intelligence Knowledge Representation.pptx
 
Lisp.pptx
Lisp.pptxLisp.pptx
Lisp.pptx
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Html introduction
Html introductionHtml introduction
Html introduction
 
Threads
ThreadsThreads
Threads
 
Types of learning
Types of learningTypes of learning
Types of learning
 
Ml introduction
Ml introductionMl introduction
Ml introduction
 
Knowledge base system
Knowledge base systemKnowledge base system
Knowledge base system
 

Recently uploaded

ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 

Recently uploaded (20)

ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 

Java Multithreading.pptx

  • 1. *
  • 2. 2 *
  • 3. 3 * *Thread: single sequential flow of control within a program *Single-threaded program can handle one task at any time. *Multitasking allows single processor to run several concurrent threads. *Most modern operating systems support multitasking.
  • 4. 4 * *Reactive systems – constantly monitoring *More responsive to user input – GUI application can interrupt a time-consuming task *Server can handle multiple clients simultaneously *Can take advantage of parallel processing *Different processes do not share memory space. *A thread can execute concurrently with other threads within a single process. *All threads managed by the JVM share memory space and can communicate with each other.
  • 6. 6 * Creating threads in Java: *Extend java.lang.Thread OR *Implement java.lang.Runnable
  • 7. 7 * Creating threads in Java: *Extend java.lang.Thread class *run() method must be overridden (similar to main method of sequential program) *run() is called when execution of the thread begins *A thread terminates when run() returns *start() method invokes run() *Calling run() does not create a new thread *Implement java.lang.Runnable interface *If already inheriting another class (i.e., JApplet) *Single method: public void run() *Thread class implements Runnable.
  • 8. 8 *
  • 9. 9 * A thread becomes Not Runnable when one of these events occurs: * Its sleep method is invoked. * The thread calls the wait method to wait for a specific condition to be satisfied. * The thread is blocked by I/O.
  • 10. 10 * java.lang.Thread +Thread() +Thread(task: Runnable) +start(): void +isAlive(): boolean +setPriority(p: int): void +join(): void +sleep(millis: long): void +yield(): void +interrupt(): void Creates a default thread. Creates a thread for a specified task. Starts the thread that causes the run() method to be invoked by the JVM. Tests whether the thread is currently running. Sets priority p (ranging from 1 to 10) for this thread. Waits for this thread to finish. Puts the runnable object to sleep for a specified time in milliseconds. Causes this thread to temporarily pause and allow other threads to execute. Interrupts this thread. «interface» java.lang.Runnable
  • 11. Method Meaning *getName Obtain a thread’s name. *getPriority Obtain a thread’s priority. *isAlive Determine if a thread is still running. *join Wait for a thread to terminate. *run Entry point for the thread. *sleep Suspend a thread for a period of time. *Start Start a thread by calling its run method.
  • 12. The Main Thread When a Java program starts up, one thread begins running immediately. This is usually called the main thread of your program, because it is the one that is executed when your program begins. The main thread is important for two reasons:  It is the thread from which other “child” threads will be spawned.  Often, it must be the last thread to finish execution because it performs various shutdown actions. Although the main thread is created automatically when your program is started, it can be controlled through a Thread object. This can be done by calling the method currentThread( ), which is a public static member of Thread. Its general form is static Thread currentThread( ) This method returns a reference to the thread in which it is called.
  • 13. 13 * class CurrentThreadDemo { public static void main(String args[]) { Thread t = Thread.currentThread(); System.out.println("Current thread: " + t); // change the name of the thread t.setName("My Thread"); System.out.println("After name change: " + t); try { for(int n = 5; n > 0; n--) { System.out.println(n); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted"); }}}
  • 14. * Current thread: Thread[main,5,main] After name change: Thread[My Thread,5,main] 5 4 3 2 1
  • 15. 15 * New Ready Thread created Finished Running start() run() Wait fortarget tofinish join() run()returns yield(), or timeout interrupt() Wait fortime out Wait tobe notified sleep() wait() Target finished notify()or notifyAll() Timeout Blocked Interrupted() A thread can be in one of five states: New, Ready, Running, Blocked, or Finished.
  • 16. 16 * You can use the yield() method to temporarily release time for other threads. public void run() { for (int i = 1; i <= lastNum; i++) { System.out.print(" " + i); Thread.yield(); } } Every time a number is printed, the print100 thread is yielded. So, the numbers are printed after the characters.
  • 17. 17 * The sleep(long mills) method puts the thread to sleep for the specified time in milliseconds. public void run() { for (int i = 1; i <= lastNum; i++) { System.out.print(" " + i); try { if (i >= 50) Thread.sleep(1); } catch (InterruptedException ex) { } } } Every time a number (>= 50) is printed, the print100 thread is put to sleep for 1 millisecond.
  • 18. 18 * You can use the join() method to force one thread to wait for another thread to finish. The numbers after 50 are printed after thread printA is finished. printA.join() -char token +getToken +setToken +paintCompone t +mouseClicked Thread print100 -char token +getToken +setToken +paintCompo net +mouseClicke d Wait for printA to finish +getToken +setToken +paintComponet Thread printA -char token +getToken +setToken +paintCompo net +mouseClicke d printA finished -char token public void run() { Thread thread4 = new Thread( new PrintChar('c', 40)); thread4.start(); try { for (int i = 1; i <= lastNum; i++) { System.out.print(" " + i); if (i == 50) thread4.join(); } } catch (InterruptedException ex) { } }
  • 19. 19 * isAlive() • method used to find out the state of a thread. • returns true: thread is in the Ready, Blocked, or Running state • returns false: thread is new and has not started or if it is finished. interrupt() f a thread is currently in the Ready or Running state, its interrupted flag is set; if a thread is currently blocked, it is awakened and enters the Ready state, and an java.io.InterruptedException is thrown. The isInterrupt() method tests whether the thread is interrupted.
  • 20. 20 * NOTE: The Thread class also contains the stop(), suspend(), and resume() methods. As of Java 2, these methods are deprecated (or outdated) because they are known to be inherently unsafe. You should assign null to a Thread variable to indicate that it is stopped rather than use the stop() method.
  • 21. 21 * // Create a second thread. class NewThread implements Runnable { Thread t; NewThread() { // Create a new, second thread t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); // Start the thread } // This is the entry point for the second thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500) ;} }
  • 22. 22 catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); }} class ThreadDemo { 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."); } }
  • 23. 23 * • Each thread is assigned a default priority of Thread.NORM_PRIORITY (constant of 5). You can reset the priority using setPriority(int priority). • Some constants for priorities include Thread.MIN_PRIORITY Thread.MAX_PRIORITY Thread.NORM_PRIORITY • By default, a thread has the priority level of the thread that created it.
  • 24. 24 // Demonstrate thread priorities. class clicker implements Runnable { long click = 0; Thread t; private volatile boolean running = true; public clicker(int p) { t = new Thread(this); t.setPriority(p); } public void run() { while (running) { click++; } } public void stop() { running = false; } public void start() { t.start(); } }
  • 25. 25 class HiLoPri { public static void main(String args[]) { Thread.currentThread().setPriority(Thread.MAX_PRIORITY); clicker hi = new clicker(Thread.NORM_PRIORITY + 2); clicker lo = new clicker(Thread.NORM_PRIORITY - 2); lo.start(); hi.start(); try { Thread.sleep(10000); } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } lo.stop(); hi.stop();
  • 26. 26 // Wait for child threads to terminate. try { hi.t.join(); lo.t.join(); } catch (InterruptedException e) { System.out.println("InterruptedException caught"); } System.out.println("Low-priority thread: " + lo.click); System.out.println("High-priority thread: " + hi.click); } } o/p : Low-priority thread: 4408112 High-priority thread: 589626904
  • 27. 27 * class NewThread implements Runnable { String name; // name of thread Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); t.start(); // Start the thread } // This is the entry point for thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(name +"Interrupted"); } System.out.println(name + " exiting."); } } class MultiThreadDemo { public static void main(String args[]) { new NewThread("One"); // start threads new NewThread("Two"); new NewThread("Three"); try { // wait for other threads to end Thread.sleep(10000); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); }System.out.println("Main thread exiting."); }}
  • 28. * *Synchronization is prevent data corruption *Synchronization allows only one thread to perform an operation on a object at a time. *If multiple threads require an access to an object, synchronization helps in maintaining consistency. *A shared resource may be corrupted if it is accessed simultaneously by multiple threads.
  • 29. * public class Counter{ private int count = 0; public int getCount(){ return count; } public setCount(int count){ this.count = count; } } *In this example, the counter tells how many access has been made. *If a thread is accessing setCount and updating count and another thread is accessing getCount at the same time, there will be inconsistency in the value of count.
  • 30. * public class Counter{ private static int count = 0; public synchronized int getCount(){ return count; } public synchoronized setCount(int count){ this.count = count; } } *By adding the synchronized keyword we make sure that when one thread is in the setCount method the other threads are all in waiting state. *The synchronized keyword places a lock on the object, and hence locks all the other methods which have the keyword synchronized. The lock does not lock the methods without the keyword synchronized and hence they are open to access by other threads.
  • 31. 31 * •Conditions can be used for communication among threads. •A thread can specify what to do under a certain condition. •newCondition() method of Lock object. •Condition methods: •await() current thread waits until the condition is signaled •signal() wakes up a waiting thread •signalAll() wakes all waiting threads «interface» java.util.concurrent.Condition +await(): void +signal(): void +signalAll(): Condition Causes the current thread to wait until the condition is signaled. Wakes up one waiting thread. Wakes up all waiting threads.
  • 32. 32 * Use the wait(), notify(), and notifyAll() methods to facilitate communication among threads. The wait(), notify(), and notifyAll() methods must be called in a synchronized method or a synchronized block on the calling object of these methods. Otherwise, an IllegalMonitorStateException would occur. The wait() method lets the thread wait until some condition occurs. When it occurs, you can use the notify() or notifyAll() methods to notify the waiting threads to resume normal execution. The notifyAll() method wakes up all waiting threads, while notify() picks up only one thread from a waiting queue.