SlideShare a Scribd company logo
Java Threads
Dr. G.Jasmine Beulah
Assistant Professor, Dept.Computer Science,
Kristu Jayanti College, Bengaluru
2
Introduction
• Performing operations concurrently (in parallel)
• We can walk, talk, breathe, see, hear, smell... all at the same time
• Computers can do this as well - download a file, print a file,
receive email, run the clock, more or less in parallel….
• How are these tasks typically accomplished?
• Operating systems support processes
• What’s the difference between a process and a thread?
• Processes have their own memory space, threads share memory
• Hence processes are “heavyweight” while threads are “lightweight”
• Most programming languages do not allow concurrency
• Usually limited to operating system "primitives" available to
systems programmers
• Java supports concurrency as part of language and libraries
3
What and why
• Threads of execution
• Each thread is a portion of a program that can execute concurrently with
other threads (multithreading)
• C and C++ are single-threaded
• Gives Java powerful capabilities not found in C and C++
• Example: downloading a video clip
• Instead of having to download the entire clip then play it:
• Download a portion, play that portion, download the next portion, play that portion...
(streaming)
Threads Concept
Multiple
threads on
multiple
CPUs
Multiple
threads
sharing a
single CPU
Thread 3
Thread 2
Thread 1
Thread 3
Thread 2
Thread 1
4
5
Creating Threads – Using Thread class
1. Declare the class as extending the Thread class.
2. Implement the run() method – responsible for executing the
sequence of code.
3. Create a thread object and call the start() method to initiate the
thread execution.
6
Creating Threads – Using Thread class
1. Declaring the class
class MyThread extends Thread
{
…..}
2. Implementing the run() method
public void run()
{ ……}
3. Starting New Thread
MyThread a1= new MyThread();
a1.start(); //invokes run() method
//Example to create threads
class A extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("From ThreadA: i= " +i);
}
System.out.println("Exit from A");
}
}
7
class B extends Thread
{
public void run()
{
for(int j=0;j<5;j++)
{
System.out.println("From ThreadB: j= " +j);
}
System.out.println("Exit from B");
}
}
8
class C extends Thread
{
public void run()
{
for(int k=0;k<5;k++)
{
System.out.println("From ThreadC: k= " +k);
}
System.out.println("Exit from K");
}
}
9
class MyThread
{
public static void main(String args[])
{
A a1=new A();
a1.start();
B b1=new B();
b1.start();
C c1=new C();
c1.start();
}}
10
Creating Threads-Using runnable interface
1. Declare the class as implementing the Runnable interface
2. Implement the run() method.
3. Create a thread by defining an object
4. Call the thread’s start() method to run the thread.
11
Creating Threads-Using runnable interface
class X implements Runnable
{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("From Thread X: = " +i);
}
System.out.println("End of ThreadX");
}
}
12
class Test
{
public static void main(String args[])
{
X a1=new X();
Thread threadX=new Thread(X);
threadX.start();
System.out.println("End of Thread");
}
}
13
Life cycle of a Thread
14
15
Thread States: Life Cycle of a Thread
• Born state
• Thread just created
• When start called, enters ready state
• Ready state (runnable state)
• Highest-priority ready thread enters running state
• Running state
• System assigns processor to thread (thread begins executing)
• When run completes or terminates, enters dead state
• Dead state
• Thread marked to be removed by system
• Entered when run terminates or throws uncaught exception
16
Thread States
• Blocked state
• Entered from running state
• Blocked thread cannot use processor, even if available
• Common reason for blocked state - waiting on I/O request
• Sleeping state
• Entered when sleep method called
• Cannot use processor
• Enters ready state after sleep time expires
• Waiting state
• Entered when wait called in an object thread is accessing
• One waiting thread becomes ready when object calls notify
• notifyAll - all waiting threads become ready
17
Thread Methods
• static void sleep( long milliseconds )
• Thread sleeps (does not contend for processor) for number of milliseconds
• Why might we want a program to invoke sleep?
• Can give lower priority threads a chance to run
• void interrupt() - interrupts a thread
• boolean isInterrupted()
• Determines if a thread is interrupted
• boolean isAlive()
• Returns true if start called and thread not dead (run has not completed)
• getPriority() - returns this thread's priority
• setPriority() – sets this threads priority
• Etc.
18
Thread Priorities and Scheduling
• All Java applets / applications are multithreaded
• Threads have priority from 1 to 10
• Thread.MIN_PRIORITY - 1
• Thread.NORM_PRIORITY - 5 (default)
• Thread.MAX_PRIORITY - 10
• New threads inherit priority of thread that created it
• Timeslicing
• Each thread gets a quantum of processor time to execute
• After time is up, processor given to next thread of equal priority
• Without timeslicing, each thread of equal priority runs to completion
19
Thread Priorities and Scheduling
• Java scheduler
• Keeps highest-priority thread running at all times
• If timeslicing available, ensure equal priority threads execute in round-robin
fashion
• New high priority threads could postpone execution of lower priority threads
• Indefinite postponement (starvation)
• Priority methods
• setPriority( int priorityNumber )
• getPriority
• yield - thread yields processor to threads of equal priority
Ad

More Related Content

What's hot (20)

Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
Haldia Institute of Technology
 
javathreads
javathreadsjavathreads
javathreads
Arjun Shanka
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
Gaurav Aggarwal
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Java Threads
Java ThreadsJava Threads
Java Threads
M Vishnuvardhan Reddy
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead Programming
Nishant Mevawala
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
caswenson
 
Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-java
aalipalh
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
koji lin
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
myrajendra
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
parag
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
Sunil OS
 
Java threading
Java threadingJava threading
Java threading
Chinh Ngo Nguyen
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Lovely Professional University
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
M. Raihan
 
Thread presentation
Thread presentationThread presentation
Thread presentation
AAshish Ojha
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
myrajendra
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
APU
 
L22 multi-threading-introduction
L22 multi-threading-introductionL22 multi-threading-introduction
L22 multi-threading-introduction
teach4uin
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead Programming
Nishant Mevawala
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
caswenson
 
Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-java
aalipalh
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
koji lin
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
myrajendra
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
parag
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
Sunil OS
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
M. Raihan
 
Thread presentation
Thread presentationThread presentation
Thread presentation
AAshish Ojha
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
myrajendra
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
APU
 
L22 multi-threading-introduction
L22 multi-threading-introductionL22 multi-threading-introduction
L22 multi-threading-introduction
teach4uin
 

Similar to Java threads (20)

Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
ssusere538f7
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
Jayant Dalvi
 
Multithreading
MultithreadingMultithreading
Multithreading
SanthiNivas
 
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbjava.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
jakjak36
 
Object-Oriented-Prog_MultiThreading.pptx
Object-Oriented-Prog_MultiThreading.pptxObject-Oriented-Prog_MultiThreading.pptx
Object-Oriented-Prog_MultiThreading.pptx
NasreenTaj20
 
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
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
Threads
ThreadsThreads
Threads
Abhishek Khune
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
TREXSHyNE
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
PreetiDixit22
 
Concept of Java Multithreading-Partially.pptx
Concept of Java Multithreading-Partially.pptxConcept of Java Multithreading-Partially.pptx
Concept of Java Multithreading-Partially.pptx
SahilKumar542
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Threads
ThreadsThreads
Threads
Nilesh Jha
 
Multi threading
Multi threadingMulti threading
Multi threading
PavanAnudeepMotiki
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
HarshaDokula
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
unit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptxunit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptx
ArunPatrick2
 
unit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptxunit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptx
ArunPatrick2
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
nehakumari0xf
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
kashyapneha2809
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
ssusere538f7
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
Jayant Dalvi
 
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbjava.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
java.pptxytbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
jakjak36
 
Object-Oriented-Prog_MultiThreading.pptx
Object-Oriented-Prog_MultiThreading.pptxObject-Oriented-Prog_MultiThreading.pptx
Object-Oriented-Prog_MultiThreading.pptx
NasreenTaj20
 
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
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
TREXSHyNE
 
Concept of Java Multithreading-Partially.pptx
Concept of Java Multithreading-Partially.pptxConcept of Java Multithreading-Partially.pptx
Concept of Java Multithreading-Partially.pptx
SahilKumar542
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
unit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptxunit3multithreadingppt-copy-180122162204.pptx
unit3multithreadingppt-copy-180122162204.pptx
ArunPatrick2
 
unit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptxunit3 Exception Handling multithreadingppt.pptx
unit3 Exception Handling multithreadingppt.pptx
ArunPatrick2
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
nehakumari0xf
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
kashyapneha2809
 
Ad

More from Dr. Jasmine Beulah Gnanadurai (20)

Chapter 4 Requirements Engineering2.pptx
Chapter 4 Requirements  Engineering2.pptxChapter 4 Requirements  Engineering2.pptx
Chapter 4 Requirements Engineering2.pptx
Dr. Jasmine Beulah Gnanadurai
 
Chapter 4 Requirement Engineering1 .pptx
Chapter 4 Requirement Engineering1 .pptxChapter 4 Requirement Engineering1 .pptx
Chapter 4 Requirement Engineering1 .pptx
Dr. Jasmine Beulah Gnanadurai
 
Chapter 2 Software Processes Processes.pptx
Chapter 2 Software Processes Processes.pptxChapter 2 Software Processes Processes.pptx
Chapter 2 Software Processes Processes.pptx
Dr. Jasmine Beulah Gnanadurai
 
Programming in Python Lists and its methods .ppt
Programming in Python Lists and its methods .pptProgramming in Python Lists and its methods .ppt
Programming in Python Lists and its methods .ppt
Dr. Jasmine Beulah Gnanadurai
 
Introduction to UML, class diagrams, sequence diagrams
Introduction to UML, class diagrams, sequence diagramsIntroduction to UML, class diagrams, sequence diagrams
Introduction to UML, class diagrams, sequence diagrams
Dr. Jasmine Beulah Gnanadurai
 
Software Process Models in Software Engineering
Software Process Models in Software EngineeringSoftware Process Models in Software Engineering
Software Process Models in Software Engineering
Dr. Jasmine Beulah Gnanadurai
 
ch03-Data Modeling Using the Entity-Relationship (ER) Model.ppt
ch03-Data Modeling Using the Entity-Relationship (ER) Model.pptch03-Data Modeling Using the Entity-Relationship (ER) Model.ppt
ch03-Data Modeling Using the Entity-Relationship (ER) Model.ppt
Dr. Jasmine Beulah Gnanadurai
 
Process Model in Software Engineering Concepts
Process Model in Software Engineering ConceptsProcess Model in Software Engineering Concepts
Process Model in Software Engineering Concepts
Dr. Jasmine Beulah Gnanadurai
 
Arrays and Detailed explanation of Array
Arrays and Detailed explanation of ArrayArrays and Detailed explanation of Array
Arrays and Detailed explanation of Array
Dr. Jasmine Beulah Gnanadurai
 
Data Warehouse_Architecture.pptx
Data Warehouse_Architecture.pptxData Warehouse_Architecture.pptx
Data Warehouse_Architecture.pptx
Dr. Jasmine Beulah Gnanadurai
 
DMQL(Data Mining Query Language).pptx
DMQL(Data Mining Query Language).pptxDMQL(Data Mining Query Language).pptx
DMQL(Data Mining Query Language).pptx
Dr. Jasmine Beulah Gnanadurai
 
Stacks.pptx
Stacks.pptxStacks.pptx
Stacks.pptx
Dr. Jasmine Beulah Gnanadurai
 
Quick Sort.pptx
Quick Sort.pptxQuick Sort.pptx
Quick Sort.pptx
Dr. Jasmine Beulah Gnanadurai
 
KBS Architecture.pptx
KBS Architecture.pptxKBS Architecture.pptx
KBS Architecture.pptx
Dr. Jasmine Beulah Gnanadurai
 
Knowledge Representation in AI.pptx
Knowledge Representation in AI.pptxKnowledge Representation in AI.pptx
Knowledge Representation in AI.pptx
Dr. Jasmine Beulah Gnanadurai
 
File allocation methods (1)
File allocation methods (1)File allocation methods (1)
File allocation methods (1)
Dr. Jasmine Beulah Gnanadurai
 
Segmentation in operating systems
Segmentation in operating systemsSegmentation in operating systems
Segmentation in operating systems
Dr. Jasmine Beulah Gnanadurai
 
Mem mgt
Mem mgtMem mgt
Mem mgt
Dr. Jasmine Beulah Gnanadurai
 
Decision tree
Decision treeDecision tree
Decision tree
Dr. Jasmine Beulah Gnanadurai
 
Association rules apriori algorithm
Association rules   apriori algorithmAssociation rules   apriori algorithm
Association rules apriori algorithm
Dr. Jasmine Beulah Gnanadurai
 
Introduction to UML, class diagrams, sequence diagrams
Introduction to UML, class diagrams, sequence diagramsIntroduction to UML, class diagrams, sequence diagrams
Introduction to UML, class diagrams, sequence diagrams
Dr. Jasmine Beulah Gnanadurai
 
ch03-Data Modeling Using the Entity-Relationship (ER) Model.ppt
ch03-Data Modeling Using the Entity-Relationship (ER) Model.pptch03-Data Modeling Using the Entity-Relationship (ER) Model.ppt
ch03-Data Modeling Using the Entity-Relationship (ER) Model.ppt
Dr. Jasmine Beulah Gnanadurai
 
Ad

Recently uploaded (20)

puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
The History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptxThe History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
Dr. Nasir Mustafa
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
Dr. Nasir Mustafa
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 

Java threads

  • 1. Java Threads Dr. G.Jasmine Beulah Assistant Professor, Dept.Computer Science, Kristu Jayanti College, Bengaluru
  • 2. 2 Introduction • Performing operations concurrently (in parallel) • We can walk, talk, breathe, see, hear, smell... all at the same time • Computers can do this as well - download a file, print a file, receive email, run the clock, more or less in parallel…. • How are these tasks typically accomplished? • Operating systems support processes • What’s the difference between a process and a thread? • Processes have their own memory space, threads share memory • Hence processes are “heavyweight” while threads are “lightweight” • Most programming languages do not allow concurrency • Usually limited to operating system "primitives" available to systems programmers • Java supports concurrency as part of language and libraries
  • 3. 3 What and why • Threads of execution • Each thread is a portion of a program that can execute concurrently with other threads (multithreading) • C and C++ are single-threaded • Gives Java powerful capabilities not found in C and C++ • Example: downloading a video clip • Instead of having to download the entire clip then play it: • Download a portion, play that portion, download the next portion, play that portion... (streaming)
  • 4. Threads Concept Multiple threads on multiple CPUs Multiple threads sharing a single CPU Thread 3 Thread 2 Thread 1 Thread 3 Thread 2 Thread 1 4
  • 5. 5 Creating Threads – Using Thread class 1. Declare the class as extending the Thread class. 2. Implement the run() method – responsible for executing the sequence of code. 3. Create a thread object and call the start() method to initiate the thread execution.
  • 6. 6 Creating Threads – Using Thread class 1. Declaring the class class MyThread extends Thread { …..} 2. Implementing the run() method public void run() { ……} 3. Starting New Thread MyThread a1= new MyThread(); a1.start(); //invokes run() method
  • 7. //Example to create threads class A extends Thread { public void run() { for(int i=0;i<5;i++) { System.out.println("From ThreadA: i= " +i); } System.out.println("Exit from A"); } } 7
  • 8. class B extends Thread { public void run() { for(int j=0;j<5;j++) { System.out.println("From ThreadB: j= " +j); } System.out.println("Exit from B"); } } 8
  • 9. class C extends Thread { public void run() { for(int k=0;k<5;k++) { System.out.println("From ThreadC: k= " +k); } System.out.println("Exit from K"); } } 9
  • 10. class MyThread { public static void main(String args[]) { A a1=new A(); a1.start(); B b1=new B(); b1.start(); C c1=new C(); c1.start(); }} 10
  • 11. Creating Threads-Using runnable interface 1. Declare the class as implementing the Runnable interface 2. Implement the run() method. 3. Create a thread by defining an object 4. Call the thread’s start() method to run the thread. 11
  • 12. Creating Threads-Using runnable interface class X implements Runnable { public void run() { for(int i=1;i<=10;i++) { System.out.println("From Thread X: = " +i); } System.out.println("End of ThreadX"); } } 12
  • 13. class Test { public static void main(String args[]) { X a1=new X(); Thread threadX=new Thread(X); threadX.start(); System.out.println("End of Thread"); } } 13
  • 14. Life cycle of a Thread 14
  • 15. 15 Thread States: Life Cycle of a Thread • Born state • Thread just created • When start called, enters ready state • Ready state (runnable state) • Highest-priority ready thread enters running state • Running state • System assigns processor to thread (thread begins executing) • When run completes or terminates, enters dead state • Dead state • Thread marked to be removed by system • Entered when run terminates or throws uncaught exception
  • 16. 16 Thread States • Blocked state • Entered from running state • Blocked thread cannot use processor, even if available • Common reason for blocked state - waiting on I/O request • Sleeping state • Entered when sleep method called • Cannot use processor • Enters ready state after sleep time expires • Waiting state • Entered when wait called in an object thread is accessing • One waiting thread becomes ready when object calls notify • notifyAll - all waiting threads become ready
  • 17. 17 Thread Methods • static void sleep( long milliseconds ) • Thread sleeps (does not contend for processor) for number of milliseconds • Why might we want a program to invoke sleep? • Can give lower priority threads a chance to run • void interrupt() - interrupts a thread • boolean isInterrupted() • Determines if a thread is interrupted • boolean isAlive() • Returns true if start called and thread not dead (run has not completed) • getPriority() - returns this thread's priority • setPriority() – sets this threads priority • Etc.
  • 18. 18 Thread Priorities and Scheduling • All Java applets / applications are multithreaded • Threads have priority from 1 to 10 • Thread.MIN_PRIORITY - 1 • Thread.NORM_PRIORITY - 5 (default) • Thread.MAX_PRIORITY - 10 • New threads inherit priority of thread that created it • Timeslicing • Each thread gets a quantum of processor time to execute • After time is up, processor given to next thread of equal priority • Without timeslicing, each thread of equal priority runs to completion
  • 19. 19 Thread Priorities and Scheduling • Java scheduler • Keeps highest-priority thread running at all times • If timeslicing available, ensure equal priority threads execute in round-robin fashion • New high priority threads could postpone execution of lower priority threads • Indefinite postponement (starvation) • Priority methods • setPriority( int priorityNumber ) • getPriority • yield - thread yields processor to threads of equal priority
  翻译: