SlideShare une entreprise Scribd logo
1  sur  19
Dr.Ranjitha M
Department of Computer Science
Kristu Jayanti College
1
 Individual and separate unit of
execution that is part of a process
 multiple threads can work together to
accomplish a common goal
 Video Game example
 one thread for graphics
 one thread for user interaction
 one thread for networking
video
interaction
networking
Video Game
Process
4
 4 separate states
 new: just created but not started
 runnable: created, started, and able to
run
 blocked: created and started but unable
to run because it is waiting for some
event to occur
 dead: thread has finished or been
stopped
new
runnable
blocked
dead
start()
stop(),
end of run method
wait(),
I/O request,
suspend()
notify(),
I/O completion,
resume()
 start(): begins a thread running
 wait() and notify(): for synchronization
 more on this later
 stop(): kills a specific thread (deprecated)
 suspend() and resume(): deprecated
 join(): wait for specific thread to finish
 setPriority(): 0 to 10 (MIN_PRIORITY to MAX_PRIORITY); 5 is
default (NORM_PRIORITY)
 highest priority thread runs
 if more than one, arbitrary
 yield(): current thread gives up
processor so another of equal
priority can run
 if none of equal priority, it runs again
 sleep(msec): stop executing for set
time
 lower priority thread can run
9
Thread class
Each thread is an object of the Thread class.
Java provide two basic ways to creates a thread:
1. Define a class that is derived class of the class Thread.
2. Make your class implement the Runnable interface
10
Simplest way is:
1. Define a class that is derived class of the class Thread.
• Object of this class is a thread.
• Provide the method called run (which will override the
inherited run method, which does nothing).
• The run method defines the code for the thread.
• Invoke the start method, which initiates the
computation of the thread
11
Example
public class HelloThread extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[ ]) {
HelloThread myThread = new HelloThread();
myThread.start();
}
}
Java entry point
Start thread and execute
run method
Create
Thread
object
12
Simpler version if name of thread object
not needed
public class HelloThread extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[ ]) {
(new HelloThread()).start();
}
} However, usually one does need the object by
name to apply other thread methods.
13
The Thread class actually implements the interface called
Runnable.
The Runnable interface defines the single method, run, meant
to contain the code executed in the thread.
Alternate more powerful way to create threads:
2. Make your class explicitly implement the Runnable
interface
14
Example
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[ ]) {
HelloRunnable myThread = new HelloRunnable();
Thread tr = new Thread(myThread); // Create Thread object
tr.start(); // Start thread and execute run method
} }
Runnable object
15
Runnable object can subclass a class other than Thread, i.e.:
public class MyRunnable extends SomeClass implements
Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[ ]) {
(new Thread(new HelloRunnable())).start();
}
}
Note: both the Thread class and the Runnable interface are part
of the standard Java libraries (java.lang package)
16
A Program with Three Java Threads using 1st method
class A extends Thread {
public void run() {
for(int i=1;i<=5;i++) System.out.println("t From ThreadA: i= "+i);
System.out.println("Exit from A");
}
}
class B extends Thread {
public void run() {
for(int j=1;j<=5;j++) System.out.println("t From ThreadB: j= "+j);
System.out.println("Exit from B");
}
}
class C extends Thread {
public void run() {
for(int k=1;k<=5;k++) System.out.println("t From ThreadC: k= "+k);
System.out.println("Exit from C");
}
}
class ThreadTest {
public static void main(String args[]) {
new A().start();
new B().start();
new C().start();
}
}
17
Run 2
From ThreadA: i= 1
From ThreadA: i= 2
From ThreadA: i= 3
From ThreadA: i= 4
From ThreadA: i= 5
From ThreadC: k= 1
From ThreadC: k= 2
From ThreadC: k= 3
From ThreadC: k= 4
From ThreadC: k= 5
Exit from C
From ThreadB: j= 1
From ThreadB: j= 2
From ThreadB: j= 3
From ThreadB: j= 4
From ThreadB: j= 5
Exit from B
Exit from A
Sample Output
From ThreadA: i= 1
From ThreadA: i= 2
From ThreadA: i= 3
From ThreadA: i= 4
From ThreadA: i= 5
Exit from A
From ThreadC: k= 1
From ThreadC: k= 2
From ThreadC: k= 3
From ThreadC: k= 4
From ThreadC: k= 5
Exit from C
From ThreadB: j= 1
From ThreadB: j= 2
From ThreadB: j= 3
From ThreadB: j= 4
From ThreadB: j= 5
Exit from B
18
Thread class
Various instance and class methods, setters and getters:
• Class methods:
• sleep()
•…
• Instance methods:
• destroy()
• interrupt()
• join()
• start()
•…
• Depreciated methods (unsafe and can cause deadlock)
• resume(), stop() suspend()
19
Thread.sleep causes the current thread to suspend execution
for a specified period.
Example
Sleep to print messages at four-second intervals:
public class SleepMessages {
public static void main(String args[]) throws InterruptedException {
String importantInfo[] = {
"Mares eat oats",
"Does eat oats",
"Little lambs eat ivy",
"A kid will eat ivy too"
};
for (int i = 0; i < importantInfo.length; i++) {
Thread.sleep(4000); //Pause for 4 seconds
System.out.println(importantInfo[i]); //Print a message
}
}
}
exception that sleep throws
when another thread
interrupts current thread
while sleep is active. Not
caught in sample code.

Contenu connexe

Tendances

Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
The Ring programming language version 1.8 book - Part 8 of 202
The Ring programming language version 1.8 book - Part 8 of 202The Ring programming language version 1.8 book - Part 8 of 202
The Ring programming language version 1.8 book - Part 8 of 202Mahmoud Samir Fayed
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threadingAPU
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAvasuraj pandey
 
L22 multi-threading-introduction
L22 multi-threading-introductionL22 multi-threading-introduction
L22 multi-threading-introductionteach4uin
 
Java concurrency
Java concurrencyJava concurrency
Java concurrencyducquoc_vn
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Python multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugamPython multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugamNavaneethan Naveen
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded ApplicationsBharat17485
 

Tendances (20)

Internet Programming with Java
Internet Programming with JavaInternet Programming with Java
Internet Programming with Java
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
The Ring programming language version 1.8 book - Part 8 of 202
The Ring programming language version 1.8 book - Part 8 of 202The Ring programming language version 1.8 book - Part 8 of 202
The Ring programming language version 1.8 book - Part 8 of 202
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Klee introduction
Klee  introductionKlee  introduction
Klee introduction
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
 
multi threading
multi threadingmulti threading
multi threading
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
 
L22 multi-threading-introduction
L22 multi-threading-introductionL22 multi-threading-introduction
L22 multi-threading-introduction
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Python multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugamPython multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugam
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded Applications
 
22 multi threading iv
22 multi threading iv22 multi threading iv
22 multi threading iv
 

Similaire à Threads (20)

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
 
Threads
ThreadsThreads
Threads
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
unit-3java.pptx
unit-3java.pptxunit-3java.pptx
unit-3java.pptx
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).ppt .
 
Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptx
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
java_threads.ppt
java_threads.pptjava_threads.ppt
java_threads.ppt
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programming
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded Programming
 

Plus de 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 JavaRanjithaM32
 
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.pptxRanjithaM32
 
Unit 1 NoSQL commands.pptx
Unit 1 NoSQL commands.pptxUnit 1 NoSQL commands.pptx
Unit 1 NoSQL commands.pptxRanjithaM32
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.pptRanjithaM32
 
ARtificial Intelligence Knowledge Representation.pptx
ARtificial Intelligence Knowledge Representation.pptxARtificial Intelligence Knowledge Representation.pptx
ARtificial Intelligence Knowledge Representation.pptxRanjithaM32
 
Html introduction
Html introductionHtml introduction
Html introductionRanjithaM32
 
Types of learning
Types of learningTypes of learning
Types of learningRanjithaM32
 
Knowledge base system
Knowledge base systemKnowledge base system
Knowledge base systemRanjithaM32
 

Plus de RanjithaM32 (12)

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
 
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
 

Dernier

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
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
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 

Dernier (20)

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
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 ...
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 

Threads

  • 1. Dr.Ranjitha M Department of Computer Science Kristu Jayanti College 1
  • 2.  Individual and separate unit of execution that is part of a process  multiple threads can work together to accomplish a common goal  Video Game example  one thread for graphics  one thread for user interaction  one thread for networking
  • 4. 4
  • 5.  4 separate states  new: just created but not started  runnable: created, started, and able to run  blocked: created and started but unable to run because it is waiting for some event to occur  dead: thread has finished or been stopped
  • 6. new runnable blocked dead start() stop(), end of run method wait(), I/O request, suspend() notify(), I/O completion, resume()
  • 7.  start(): begins a thread running  wait() and notify(): for synchronization  more on this later  stop(): kills a specific thread (deprecated)  suspend() and resume(): deprecated  join(): wait for specific thread to finish  setPriority(): 0 to 10 (MIN_PRIORITY to MAX_PRIORITY); 5 is default (NORM_PRIORITY)
  • 8.  highest priority thread runs  if more than one, arbitrary  yield(): current thread gives up processor so another of equal priority can run  if none of equal priority, it runs again  sleep(msec): stop executing for set time  lower priority thread can run
  • 9. 9 Thread class Each thread is an object of the Thread class. Java provide two basic ways to creates a thread: 1. Define a class that is derived class of the class Thread. 2. Make your class implement the Runnable interface
  • 10. 10 Simplest way is: 1. Define a class that is derived class of the class Thread. • Object of this class is a thread. • Provide the method called run (which will override the inherited run method, which does nothing). • The run method defines the code for the thread. • Invoke the start method, which initiates the computation of the thread
  • 11. 11 Example public class HelloThread extends Thread { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[ ]) { HelloThread myThread = new HelloThread(); myThread.start(); } } Java entry point Start thread and execute run method Create Thread object
  • 12. 12 Simpler version if name of thread object not needed public class HelloThread extends Thread { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[ ]) { (new HelloThread()).start(); } } However, usually one does need the object by name to apply other thread methods.
  • 13. 13 The Thread class actually implements the interface called Runnable. The Runnable interface defines the single method, run, meant to contain the code executed in the thread. Alternate more powerful way to create threads: 2. Make your class explicitly implement the Runnable interface
  • 14. 14 Example public class HelloRunnable implements Runnable { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[ ]) { HelloRunnable myThread = new HelloRunnable(); Thread tr = new Thread(myThread); // Create Thread object tr.start(); // Start thread and execute run method } } Runnable object
  • 15. 15 Runnable object can subclass a class other than Thread, i.e.: public class MyRunnable extends SomeClass implements Runnable { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[ ]) { (new Thread(new HelloRunnable())).start(); } } Note: both the Thread class and the Runnable interface are part of the standard Java libraries (java.lang package)
  • 16. 16 A Program with Three Java Threads using 1st method class A extends Thread { public void run() { for(int i=1;i<=5;i++) System.out.println("t From ThreadA: i= "+i); System.out.println("Exit from A"); } } class B extends Thread { public void run() { for(int j=1;j<=5;j++) System.out.println("t From ThreadB: j= "+j); System.out.println("Exit from B"); } } class C extends Thread { public void run() { for(int k=1;k<=5;k++) System.out.println("t From ThreadC: k= "+k); System.out.println("Exit from C"); } } class ThreadTest { public static void main(String args[]) { new A().start(); new B().start(); new C().start(); } }
  • 17. 17 Run 2 From ThreadA: i= 1 From ThreadA: i= 2 From ThreadA: i= 3 From ThreadA: i= 4 From ThreadA: i= 5 From ThreadC: k= 1 From ThreadC: k= 2 From ThreadC: k= 3 From ThreadC: k= 4 From ThreadC: k= 5 Exit from C From ThreadB: j= 1 From ThreadB: j= 2 From ThreadB: j= 3 From ThreadB: j= 4 From ThreadB: j= 5 Exit from B Exit from A Sample Output From ThreadA: i= 1 From ThreadA: i= 2 From ThreadA: i= 3 From ThreadA: i= 4 From ThreadA: i= 5 Exit from A From ThreadC: k= 1 From ThreadC: k= 2 From ThreadC: k= 3 From ThreadC: k= 4 From ThreadC: k= 5 Exit from C From ThreadB: j= 1 From ThreadB: j= 2 From ThreadB: j= 3 From ThreadB: j= 4 From ThreadB: j= 5 Exit from B
  • 18. 18 Thread class Various instance and class methods, setters and getters: • Class methods: • sleep() •… • Instance methods: • destroy() • interrupt() • join() • start() •… • Depreciated methods (unsafe and can cause deadlock) • resume(), stop() suspend()
  • 19. 19 Thread.sleep causes the current thread to suspend execution for a specified period. Example Sleep to print messages at four-second intervals: public class SleepMessages { public static void main(String args[]) throws InterruptedException { String importantInfo[] = { "Mares eat oats", "Does eat oats", "Little lambs eat ivy", "A kid will eat ivy too" }; for (int i = 0; i < importantInfo.length; i++) { Thread.sleep(4000); //Pause for 4 seconds System.out.println(importantInfo[i]); //Print a message } } } exception that sleep throws when another thread interrupts current thread while sleep is active. Not caught in sample code.