SlideShare une entreprise Scribd logo
1  sur  12
Télécharger pour lire hors ligne
Using isAlive( ) and join( )
• We want the main thread to finish last. In the preceding examples,
this is accomplished by calling sleep( ) within main( ), with a long
enough delay to ensure that all child threads terminate prior to the
main thread. But it is unsatisfactory solution.
Q- How can one thread know when another thread has
ended?
Ans- Two ways exist to determine whether a thread has
finished.
First, you can call isAlive( ) on the thread.
This method is defined by Thread, and its general form is
final boolean isAlive( )
The isAlive( ) method returns true if the thread upon
which it is called is still running. It returns false otherwise.
2. use to wait for a thread to finish is called join( ):
final void join( ) throws InterruptedException
• This method waits until the thread on which it is
called terminates. Its name comes from the
concept of the calling thread waiting until the
specified thread joins it.
• Additional forms of join( ) allow you to specify a
maximum amount of time that you want to wait
for the specified thread to terminate.
class C extends Thread{
C(String name) {
super(name); }
public void run() {
for(int k=1;k<=5;k++){
System.out.println("t From Thread "+this.getName()+" :k= "+k);
}
System.out.println("Exit From "+this.getName());
} }
class test {
public static void main(String args[]) {
C th1=new C("th1");
C th2=new C("th2");
C th3=new C("th3");
th1.start();
th2.start();
th3.start();
System.out.println("Thread One is alive: "+ th1.isAlive());
System.out.println("Thread Two is alive: "+ th2.isAlive());
System.out.println("Thread Three is alive: "+ th3.isAlive());
try {
System.out.println("Waiting for threads to finish.");
th1.join();
th2.join();
th3.join();
}
catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
C:>java test
Thread One is alive: true
Thread Two is alive: true
Thread Three is alive: true
Waiting for threads to finish.
From Thread th2 :k= 1
……..
From Thread th2 :k= 5
Exit From th2
From Thread th3 :k= 1
………….
From Thread th3 :k= 5
Exit From th3
From Thread th1 :k= 1
From Thread th1 :k= 2
From Thread th1 :k= 3
From Thread th1 :k= 4
From Thread th1 :k= 5
Exit From th1
Main thread exiting.
• In the previous code the join method in main
waits for all the child threads to complete. Thus
the main thread completes in the last.
• If join statement are removed then it may be
possible that the main thread exits before the
child threads.
• The case may also occur that before printing the
status of a child thread in main thread(by isAlive()
method), the child thread is already finished/exit.
In that case the isAlive() will return false.
Thread Priorities
• Used by the thread scheduler to decide when each thread
should be allowed to run. In theory, higher-priority threads
get more CPU time than lower-priority threads.
• In practice, the amount of CPU time that a thread gets
often depends on several factors besides its priority. (For
example, how an operating system implements
multitasking can affect the relative availability of CPU time.)
• A higher-priority thread can also preempt a lower-priority
one. For instance, when a lower-priority thread is running
and a higher-priority thread resumes (from sleeping or
waiting on I/O, for example), it will preempt the lower-
priority thread.
• To set a thread’s priority, use the setPriority( ) method,
which is a member of Thread. This is its general form:
final void setPriority(int level)
• level specifies the new priority setting for the
calling thread. The value of level must be
within the range MIN_PRIORITY and
MAX_PRIORITY. Currently, these values are 1
and 10, respectively. To return a thread to
default priority, specify NORM_PRIORITY,
which is currently 5.
• These priorities are defined as final variables
within Thread class.
• The high priority should be used very carefully
as it affect the other threads.
class A extends Thread {
int count1;
private volatile boolean flag1 = true;
public void run() {
while(flag1) {
count1++;
} }
public void stop1() {
flag1 = false;
} }
class B extends Thread{
int count2;
private volatile boolean flag2 = true;
public void run() {
while(flag2) {
count2++;
} }
public void stop1() {
flag2 = false;
} }
class test {
public static void main(String args[]) {
A threadA =new A();
B threadB =new B();
threadB.setPriority(Thread.MAX_PRIORITY);//5+1
threadA.setPriority(Thread.MIN_PRIORITY);//1
System.out.println("Start Thread A"); threadA.start();
System.out.println("Start Thread B"); threadB.start();
try { Thread.sleep(1000); }
catch (InterruptedException e) {
System.out.println("Main thread interrupted."); }
threadA.stop1();
threadB.stop1();
System.out.println("High-priority thread: " + threadB.count2);
System.out.println("Low-priority thread: " + threadA.count1);
System.out.println("End of Main Thread ");
} }
C:>java test
Start Thread A
Start Thread B
High-priority thread: 461821456
Low-priority thread: 439896882
End of Main Thread
• The output of this code is not fixed and will be
different for each run. But the count value of
high priority thread will always be higher then
that of lower priority thread.

Contenu connexe

Tendances

XLnet RoBERTa Reformer
XLnet RoBERTa ReformerXLnet RoBERTa Reformer
XLnet RoBERTa ReformerSan Kim
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded ApplicationsBharat17485
 
Ruby Concurrency & Threads
Ruby Concurrency & ThreadsRuby Concurrency & Threads
Ruby Concurrency & ThreadsAnup Nivargi
 
Threads c sharp
Threads c sharpThreads c sharp
Threads c sharpDeivaa
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 
Lecture01a correctness
Lecture01a correctnessLecture01a correctness
Lecture01a correctnessSonia Djebali
 
Dotnet programming concepts difference faqs- 3
Dotnet programming concepts difference faqs- 3Dotnet programming concepts difference faqs- 3
Dotnet programming concepts difference faqs- 3Umar Ali
 
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)teach4uin
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)teach4uin
 

Tendances (20)

String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java thread
Java threadJava thread
Java thread
 
XLnet RoBERTa Reformer
XLnet RoBERTa ReformerXLnet RoBERTa Reformer
XLnet RoBERTa Reformer
 
Jsp session 12
Jsp   session 12Jsp   session 12
Jsp session 12
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded Applications
 
C# Thread synchronization
C# Thread synchronizationC# Thread synchronization
C# Thread synchronization
 
Java threads
Java threadsJava threads
Java threads
 
Ruby Concurrency & Threads
Ruby Concurrency & ThreadsRuby Concurrency & Threads
Ruby Concurrency & Threads
 
Threads c sharp
Threads c sharpThreads c sharp
Threads c sharp
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Java String
Java StringJava String
Java String
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
 
Lecture01a correctness
Lecture01a correctnessLecture01a correctness
Lecture01a correctness
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Dotnet programming concepts difference faqs- 3
Dotnet programming concepts difference faqs- 3Dotnet programming concepts difference faqs- 3
Dotnet programming concepts difference faqs- 3
 
Java String
Java String Java String
Java String
 
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)
 

En vedette

En vedette (20)

17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - ii
 
Ch11 communication
Ch11  communicationCh11  communication
Ch11 communication
 
Introduction of reflection
Introduction of reflection Introduction of reflection
Introduction of reflection
 
26 io -ii file handling
26  io -ii  file handling26  io -ii  file handling
26 io -ii file handling
 
28 networking
28  networking28  networking
28 networking
 
22 multi threading iv
22 multi threading iv22 multi threading iv
22 multi threading iv
 
Lecture 5 phasor notations
Lecture 5 phasor notationsLecture 5 phasor notations
Lecture 5 phasor notations
 
Vlsi
VlsiVlsi
Vlsi
 
Fiber optics101
Fiber optics101Fiber optics101
Fiber optics101
 
Spread spectrum
Spread spectrumSpread spectrum
Spread spectrum
 
16 exception handling - i
16 exception handling - i16 exception handling - i
16 exception handling - i
 
T com presentation (error correcting code)
T com presentation   (error correcting code)T com presentation   (error correcting code)
T com presentation (error correcting code)
 
Low noise amplifier csd
Low noise amplifier csdLow noise amplifier csd
Low noise amplifier csd
 
Digital Communication 2
Digital Communication 2Digital Communication 2
Digital Communication 2
 
Line coding
Line codingLine coding
Line coding
 
Digital Communication 4
Digital Communication 4Digital Communication 4
Digital Communication 4
 
Limits
LimitsLimits
Limits
 
Trigonometry101
Trigonometry101Trigonometry101
Trigonometry101
 
Analytic geometry lecture2
Analytic geometry lecture2Analytic geometry lecture2
Analytic geometry lecture2
 
Data Communication 1
Data Communication 1Data Communication 1
Data Communication 1
 

Similaire à 21 multi threading - iii

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.pptTabassumMaktum
 
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.pptTabassumMaktum
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaMonika Mishra
 
Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptxRanjithaM32
 
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 languagearnavytstudio2814
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptxramyan49
 
Multithreadingppt.pptx
Multithreadingppt.pptxMultithreadingppt.pptx
Multithreadingppt.pptxHKShab
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
Threads and Synchronization in c#
Threads and Synchronization in c#Threads and Synchronization in c#
Threads and Synchronization in c#Rizwan Ali
 
Threads And Synchronization in C#
Threads And Synchronization in C#Threads And Synchronization in C#
Threads And Synchronization in C#Rizwan Ali
 

Similaire à 21 multi threading - iii (20)

Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
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 Thread
Java ThreadJava Thread
Java Thread
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Threading concepts
Threading conceptsThreading concepts
Threading concepts
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Internet Programming with Java
Internet Programming with JavaInternet Programming with Java
Internet Programming with Java
 
Java
JavaJava
Java
 
Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptx
 
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
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Multithreadingppt.pptx
Multithreadingppt.pptxMultithreadingppt.pptx
Multithreadingppt.pptx
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Threads and Synchronization in c#
Threads and Synchronization in c#Threads and Synchronization in c#
Threads and Synchronization in c#
 
Threads And Synchronization in C#
Threads And Synchronization in C#Threads And Synchronization in C#
Threads And Synchronization in C#
 
Threads
ThreadsThreads
Threads
 
Multithreading
MultithreadingMultithreading
Multithreading
 

Dernier

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 

Dernier (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 

21 multi threading - iii

  • 1. Using isAlive( ) and join( ) • We want the main thread to finish last. In the preceding examples, this is accomplished by calling sleep( ) within main( ), with a long enough delay to ensure that all child threads terminate prior to the main thread. But it is unsatisfactory solution. Q- How can one thread know when another thread has ended? Ans- Two ways exist to determine whether a thread has finished. First, you can call isAlive( ) on the thread. This method is defined by Thread, and its general form is final boolean isAlive( ) The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false otherwise.
  • 2. 2. use to wait for a thread to finish is called join( ): final void join( ) throws InterruptedException • This method waits until the thread on which it is called terminates. Its name comes from the concept of the calling thread waiting until the specified thread joins it. • Additional forms of join( ) allow you to specify a maximum amount of time that you want to wait for the specified thread to terminate.
  • 3. class C extends Thread{ C(String name) { super(name); } public void run() { for(int k=1;k<=5;k++){ System.out.println("t From Thread "+this.getName()+" :k= "+k); } System.out.println("Exit From "+this.getName()); } } class test { public static void main(String args[]) { C th1=new C("th1"); C th2=new C("th2"); C th3=new C("th3"); th1.start(); th2.start(); th3.start();
  • 4. System.out.println("Thread One is alive: "+ th1.isAlive()); System.out.println("Thread Two is alive: "+ th2.isAlive()); System.out.println("Thread Three is alive: "+ th3.isAlive()); try { System.out.println("Waiting for threads to finish."); th1.join(); th2.join(); th3.join(); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Main thread exiting."); } }
  • 5. C:>java test Thread One is alive: true Thread Two is alive: true Thread Three is alive: true Waiting for threads to finish. From Thread th2 :k= 1 …….. From Thread th2 :k= 5 Exit From th2 From Thread th3 :k= 1 …………. From Thread th3 :k= 5 Exit From th3 From Thread th1 :k= 1 From Thread th1 :k= 2 From Thread th1 :k= 3 From Thread th1 :k= 4 From Thread th1 :k= 5 Exit From th1 Main thread exiting.
  • 6. • In the previous code the join method in main waits for all the child threads to complete. Thus the main thread completes in the last. • If join statement are removed then it may be possible that the main thread exits before the child threads. • The case may also occur that before printing the status of a child thread in main thread(by isAlive() method), the child thread is already finished/exit. In that case the isAlive() will return false.
  • 7.
  • 8. Thread Priorities • Used by the thread scheduler to decide when each thread should be allowed to run. In theory, higher-priority threads get more CPU time than lower-priority threads. • In practice, the amount of CPU time that a thread gets often depends on several factors besides its priority. (For example, how an operating system implements multitasking can affect the relative availability of CPU time.) • A higher-priority thread can also preempt a lower-priority one. For instance, when a lower-priority thread is running and a higher-priority thread resumes (from sleeping or waiting on I/O, for example), it will preempt the lower- priority thread. • To set a thread’s priority, use the setPriority( ) method, which is a member of Thread. This is its general form: final void setPriority(int level)
  • 9. • level specifies the new priority setting for the calling thread. The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively. To return a thread to default priority, specify NORM_PRIORITY, which is currently 5. • These priorities are defined as final variables within Thread class. • The high priority should be used very carefully as it affect the other threads.
  • 10. class A extends Thread { int count1; private volatile boolean flag1 = true; public void run() { while(flag1) { count1++; } } public void stop1() { flag1 = false; } } class B extends Thread{ int count2; private volatile boolean flag2 = true; public void run() { while(flag2) { count2++; } } public void stop1() { flag2 = false; } }
  • 11. class test { public static void main(String args[]) { A threadA =new A(); B threadB =new B(); threadB.setPriority(Thread.MAX_PRIORITY);//5+1 threadA.setPriority(Thread.MIN_PRIORITY);//1 System.out.println("Start Thread A"); threadA.start(); System.out.println("Start Thread B"); threadB.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } threadA.stop1(); threadB.stop1(); System.out.println("High-priority thread: " + threadB.count2); System.out.println("Low-priority thread: " + threadA.count1); System.out.println("End of Main Thread "); } }
  • 12. C:>java test Start Thread A Start Thread B High-priority thread: 461821456 Low-priority thread: 439896882 End of Main Thread • The output of this code is not fixed and will be different for each run. But the count value of high priority thread will always be higher then that of lower priority thread.