SlideShare ist ein Scribd-Unternehmen logo
1 von 12
Downloaden Sie, um offline zu lesen
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.

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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)
 

Andere mochten auch

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 

Kürzlich hochgeladen (20)

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 

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.