SlideShare una empresa de Scribd logo
1 de 12
Descargar para leer sin conexión
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.

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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)
 

Destacado

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

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

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

Último

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 

Último (20)

Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 

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.