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

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
🐬 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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer 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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
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
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 

Último (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer 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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
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
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of 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.