SlideShare a Scribd company logo
1 of 19
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

More Related Content

What's hot

Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead ProgrammingNishant Mevawala
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronizationcaswenson
 
Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-javaaalipalh
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Javakoji lin
 
Thread model of java
Thread model of javaThread model of java
Thread model of javamyrajendra
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in JavaM. Raihan
 
Thread presentation
Thread presentationThread presentation
Thread presentationAAshish Ojha
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37myrajendra
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threadingAPU
 
L22 multi-threading-introduction
L22 multi-threading-introductionL22 multi-threading-introduction
L22 multi-threading-introductionteach4uin
 

What's hot (20)

Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
javathreads
javathreadsjavathreads
javathreads
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead Programming
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
 
Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-java
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Java threading
Java threadingJava threading
Java threading
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
 
Thread presentation
Thread presentationThread presentation
Thread presentation
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
 
L22 multi-threading-introduction
L22 multi-threading-introductionL22 multi-threading-introduction
L22 multi-threading-introduction
 

Similar to Java threads

Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreadingssusere538f7
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in JavaJayant Dalvi
 
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.pptxArulmozhivarman8
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaMonika Mishra
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptxTREXSHyNE
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024nehakumari0xf
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024kashyapneha2809
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptxmadan r
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptxnimbalkarvikram966
 
Java class 6
Java class 6Java class 6
Java class 6Edureka!
 

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
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Multithreading
MultithreadingMultithreading
Multithreading
 
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
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Threads
ThreadsThreads
Threads
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Threads
ThreadsThreads
Threads
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
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
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
 
MULTI THREADING.pptx
MULTI THREADING.pptxMULTI THREADING.pptx
MULTI THREADING.pptx
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
Java class 6
Java class 6Java class 6
Java class 6
 
Threading concepts
Threading conceptsThreading concepts
Threading concepts
 

More from Dr. Jasmine Beulah Gnanadurai

More from Dr. Jasmine Beulah Gnanadurai (20)

Data Warehouse_Architecture.pptx
Data Warehouse_Architecture.pptxData Warehouse_Architecture.pptx
Data Warehouse_Architecture.pptx
 
DMQL(Data Mining Query Language).pptx
DMQL(Data Mining Query Language).pptxDMQL(Data Mining Query Language).pptx
DMQL(Data Mining Query Language).pptx
 
Stacks.pptx
Stacks.pptxStacks.pptx
Stacks.pptx
 
Quick Sort.pptx
Quick Sort.pptxQuick Sort.pptx
Quick Sort.pptx
 
KBS Architecture.pptx
KBS Architecture.pptxKBS Architecture.pptx
KBS Architecture.pptx
 
Knowledge Representation in AI.pptx
Knowledge Representation in AI.pptxKnowledge Representation in AI.pptx
Knowledge Representation in AI.pptx
 
File allocation methods (1)
File allocation methods (1)File allocation methods (1)
File allocation methods (1)
 
Segmentation in operating systems
Segmentation in operating systemsSegmentation in operating systems
Segmentation in operating systems
 
Mem mgt
Mem mgtMem mgt
Mem mgt
 
Decision tree
Decision treeDecision tree
Decision tree
 
Association rules apriori algorithm
Association rules   apriori algorithmAssociation rules   apriori algorithm
Association rules apriori algorithm
 
Big data architecture
Big data architectureBig data architecture
Big data architecture
 
Knowledge representation
Knowledge representationKnowledge representation
Knowledge representation
 
Aritificial intelligence
Aritificial intelligenceAritificial intelligence
Aritificial intelligence
 
Java Applets
Java AppletsJava Applets
Java Applets
 
Stacks and Queue - Data Structures
Stacks and Queue - Data StructuresStacks and Queue - Data Structures
Stacks and Queue - Data Structures
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
JavaScript Operators
JavaScript OperatorsJavaScript Operators
JavaScript Operators
 
Css Text Formatting
Css Text FormattingCss Text Formatting
Css Text Formatting
 
CSS - Cascading Style Sheet
CSS - Cascading Style SheetCSS - Cascading Style Sheet
CSS - Cascading Style Sheet
 

Recently uploaded

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 

Recently uploaded (20)

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 

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