SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Thread Priorities




                    1
Objectives



On completion of this period, you would be
able to learn
• Concepts of thread priority
• Relevant methods and constants
• Example program




                                             2
Recap
• Before discussing thread priority, let’s quickly
  recollect some concepts on thread
   • Java provides two ways for creating threads
      • By extending Thread class
      • By implementing Runnable interface
   • In each of these ways
      • run() method has to be overridden /
        implemented
      • run() method is the body of the thread
   • We use start() method to start the thread
   • start() method in-turn calls run() method
                                                     3
Concepts of Thread Priority

• In operating systems, we learnt the CPU
  scheduling algorithms
• Priority scheduling is one of them
• Higher priority processes will be scheduled first
• The same concept can be applied to threads also




                                                      4
Concepts of Thread Priority contd..
• Why priorities?
   • Determine which thread receives CPU control and gets to be
     executed first
• Definition:
   • Integer value ranging from 1 to 10
   • Higher the thread priority larger chance of being executed first
   • Example:
       • Two threads are ready to run
       • First thread: priority of 5, already running
       • Second thread : priority of 10, comes in while first thread is
         running
       • First thread will be preempted from CPU and the CPU will
         allotted to the second thread

                                                                      5
Concepts of Thread Priority contd..
• Context switch
   • Occurs when a thread snatches the control of CPU from
     another
   • When does it occur?
      • Running thread voluntarily relinquishes CPU control
      • Running thread is preempted by a higher priority
        thread
• More than one highest priority thread that is ready to run
   • Deciding which receives CPU control depends on the
     operating system
      • Windows 95/98/NT: Uses time-sliced round-robin
      • Solaris: Executing thread should voluntarily
        relinquish CPU control
                                                               6
Thread Constants

• Thread priority constants

  • Thread.MIN_PRIORITY – 1

  • Thread.NORM_PRIORITY - 5 (default)

  • Thread.MAX_PRIORITY – 10



                                         7
Thread Constants contd..
• When we create a thread directly (not inheriting
  any other thread)
   • The priority of that thread is
     NORM_PRIORITY

• Inherited thread gets the priority of its parent
  thread




                                                     8
Thread Priority methods
• Priority related methods
  • setPriority( int priorityNumber )
      • sets the priority of the thread

   • getPriority( )
      • returns the priority value of a thread




                                                 9
Example Program
class clicker implements Runnable {
 int click = 0;
 Thread t;
 private volatile boolean running = true;
 public clicker(int p) {
   t = new Thread(this);
   t.setPriority(p);
 }
 public void run() {        Setting the priority

   while (running) {
     click++;
   }
 }                                                 10
Example Program

    public void stop() {
      running = false;
    }

    public void start() {
      t.start();
    }
}




                                    11
Example Program                    Contd..
class HiLoPri {
 public static void main (String args[]) {
   Thread. current Thread(). setPriority (Thread. MAX_PRIORITY);
   clicker hi = new clicker (Thread. NORM_PRIORITY + 2);
   clicker lo = new clicker (Thread. NORM_PRIORITY - 2);

  lo. start();
                                                          Using Priority
  hi. start();                                            constants
  try {
    Thread.sleep(5000);
  } catch (Interrupted Exception e) {
     System. out. println ("Main thread interrupted.");
  }

                                                                           12
Example Program
        lo.stop();
        hi.stop();
        // Wait for child threads to terminate.
        try {
          hi.t.join();
          lo.t.join();
        } catch (InterruptedException e) {
          System.out.println("InterruptedException caught");
        }
        System.out.println("Low-priority thread: " + lo.click);
        System.out.println("High-priority thread: " + hi.click);
    }
}

                                                                   13
Example Program Contd..


Output




         For the given 5 seconds
              The higher priority thread get more number of clicks
              compared to the lower priority thread




                                                                      14
Summary

• In this class you have learnt
   • The thread priority concepts
   • Thread’s priority related constants
   • Thread’s priority related methods
   • An example program to demonstrate thread
     priority




                                                15
Frequently Asked Questions
1. Explain the concept of thread priority
2. Which methods are useful for working with thread
   priority ?
3. List the thread priority constants




                                                      16
Quiz
1. What is the range of thread priorities in Java?
   1.   0 to 10
   2.   1 to 10
   3.   1 to 20
   4.   Any number




                                                     17
Quiz Contd..

2.What is the default priority set for a newly
   created thread ?
  1. MAX_PRIORITY
  2. MIN_PRIORITY
  3. NORM_PRIORITY
  4. No priority is set
Quiz Contd..
3.Which is NOT a thread priority related method ?
  1.   setPriority ()
  2.   setPriorities()
  3.   yield()
  4.   getPriority()




                                                    19
Quiz

4.If the thread priority is higher
    1. Less chance for it to get executed first
    2. Greater chance for it to get executed first
    3. Equal chance for it to get executed first
    4. No chance for it to get executed first
Assignments

• Write Java programs to create two threads, one
  printing odd numbers and the other printing even
  numbers
• Set the priority as MAX_PRIORITY - 2 for the first
  thread and MIN_PRIORITY + 3 for the second
  thread
• Write an application in Java to test the two threads




                                                     21

Weitere ähnliche Inhalte

Was ist angesagt?

Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-javaaalipalh
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
L22 multi-threading-introduction
L22 multi-threading-introductionL22 multi-threading-introduction
L22 multi-threading-introductionteach4uin
 
Multi threading
Multi threadingMulti threading
Multi threadinggndu
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded ApplicationsBharat17485
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-threadjavaicon
 
Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreadingjehan1987
 
Java Multithreading
Java MultithreadingJava Multithreading
Java MultithreadingRajkattamuri
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAvasuraj pandey
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaArafat Hossan
 

Was ist angesagt? (20)

Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-java
 
javathreads
javathreadsjavathreads
javathreads
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Java threading
Java threadingJava threading
Java threading
 
L22 multi-threading-introduction
L22 multi-threading-introductionL22 multi-threading-introduction
L22 multi-threading-introduction
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded Applications
 
Threads in java
Threads in javaThreads in java
Threads in java
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-thread
 
Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreading
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 

Ähnlich wie Thread priorities35

Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreadingssusere538f7
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024nehakumari0xf
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024kashyapneha2809
 
ThreadProperties
ThreadPropertiesThreadProperties
ThreadPropertiesmyrajendra
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxArulmozhivarman8
 
JAVA THREADS.pdf
JAVA THREADS.pdfJAVA THREADS.pdf
JAVA THREADS.pdfMohit Kumar
 
Java class 6
Java class 6Java class 6
Java class 6Edureka!
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptxmadan r
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaMonika Mishra
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in JavaJayant Dalvi
 

Ähnlich wie Thread priorities35 (20)

Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Threads
ThreadsThreads
Threads
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
 
Threads
ThreadsThreads
Threads
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
 
ThreadProperties
ThreadPropertiesThreadProperties
ThreadProperties
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
 
Multi Threading
Multi ThreadingMulti Threading
Multi Threading
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Threading concepts
Threading conceptsThreading concepts
Threading concepts
 
Multithreading
MultithreadingMultithreading
Multithreading
 
JAVA THREADS.pdf
JAVA THREADS.pdfJAVA THREADS.pdf
JAVA THREADS.pdf
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
 
Java class 6
Java class 6Java class 6
Java class 6
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
 
Java Thread
Java ThreadJava Thread
Java Thread
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 

Mehr von myrajendra (20)

Fundamentals
FundamentalsFundamentals
Fundamentals
 
Data type
Data typeData type
Data type
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
 
Jdbc workflow
Jdbc workflowJdbc workflow
Jdbc workflow
 
2 jdbc drivers
2 jdbc drivers2 jdbc drivers
2 jdbc drivers
 
3 jdbc api
3 jdbc api3 jdbc api
3 jdbc api
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
 
Dao example
Dao exampleDao example
Dao example
 
Sessionex1
Sessionex1Sessionex1
Sessionex1
 
Internal
InternalInternal
Internal
 
3. elements
3. elements3. elements
3. elements
 
2. attributes
2. attributes2. attributes
2. attributes
 
1 introduction to html
1 introduction to html1 introduction to html
1 introduction to html
 
Headings
HeadingsHeadings
Headings
 
Forms
FormsForms
Forms
 
Css
CssCss
Css
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Starting jdbc
Starting jdbcStarting jdbc
Starting jdbc
 

Thread priorities35

  • 2. Objectives On completion of this period, you would be able to learn • Concepts of thread priority • Relevant methods and constants • Example program 2
  • 3. Recap • Before discussing thread priority, let’s quickly recollect some concepts on thread • Java provides two ways for creating threads • By extending Thread class • By implementing Runnable interface • In each of these ways • run() method has to be overridden / implemented • run() method is the body of the thread • We use start() method to start the thread • start() method in-turn calls run() method 3
  • 4. Concepts of Thread Priority • In operating systems, we learnt the CPU scheduling algorithms • Priority scheduling is one of them • Higher priority processes will be scheduled first • The same concept can be applied to threads also 4
  • 5. Concepts of Thread Priority contd.. • Why priorities? • Determine which thread receives CPU control and gets to be executed first • Definition: • Integer value ranging from 1 to 10 • Higher the thread priority larger chance of being executed first • Example: • Two threads are ready to run • First thread: priority of 5, already running • Second thread : priority of 10, comes in while first thread is running • First thread will be preempted from CPU and the CPU will allotted to the second thread 5
  • 6. Concepts of Thread Priority contd.. • Context switch • Occurs when a thread snatches the control of CPU from another • When does it occur? • Running thread voluntarily relinquishes CPU control • Running thread is preempted by a higher priority thread • More than one highest priority thread that is ready to run • Deciding which receives CPU control depends on the operating system • Windows 95/98/NT: Uses time-sliced round-robin • Solaris: Executing thread should voluntarily relinquish CPU control 6
  • 7. Thread Constants • Thread priority constants • Thread.MIN_PRIORITY – 1 • Thread.NORM_PRIORITY - 5 (default) • Thread.MAX_PRIORITY – 10 7
  • 8. Thread Constants contd.. • When we create a thread directly (not inheriting any other thread) • The priority of that thread is NORM_PRIORITY • Inherited thread gets the priority of its parent thread 8
  • 9. Thread Priority methods • Priority related methods • setPriority( int priorityNumber ) • sets the priority of the thread • getPriority( ) • returns the priority value of a thread 9
  • 10. Example Program class clicker implements Runnable { int click = 0; Thread t; private volatile boolean running = true; public clicker(int p) { t = new Thread(this); t.setPriority(p); } public void run() { Setting the priority while (running) { click++; } } 10
  • 11. Example Program public void stop() { running = false; } public void start() { t.start(); } } 11
  • 12. Example Program Contd.. class HiLoPri { public static void main (String args[]) { Thread. current Thread(). setPriority (Thread. MAX_PRIORITY); clicker hi = new clicker (Thread. NORM_PRIORITY + 2); clicker lo = new clicker (Thread. NORM_PRIORITY - 2); lo. start(); Using Priority hi. start(); constants try { Thread.sleep(5000); } catch (Interrupted Exception e) { System. out. println ("Main thread interrupted."); } 12
  • 13. Example Program lo.stop(); hi.stop(); // Wait for child threads to terminate. try { hi.t.join(); lo.t.join(); } catch (InterruptedException e) { System.out.println("InterruptedException caught"); } System.out.println("Low-priority thread: " + lo.click); System.out.println("High-priority thread: " + hi.click); } } 13
  • 14. Example Program Contd.. Output For the given 5 seconds The higher priority thread get more number of clicks compared to the lower priority thread 14
  • 15. Summary • In this class you have learnt • The thread priority concepts • Thread’s priority related constants • Thread’s priority related methods • An example program to demonstrate thread priority 15
  • 16. Frequently Asked Questions 1. Explain the concept of thread priority 2. Which methods are useful for working with thread priority ? 3. List the thread priority constants 16
  • 17. Quiz 1. What is the range of thread priorities in Java? 1. 0 to 10 2. 1 to 10 3. 1 to 20 4. Any number 17
  • 18. Quiz Contd.. 2.What is the default priority set for a newly created thread ? 1. MAX_PRIORITY 2. MIN_PRIORITY 3. NORM_PRIORITY 4. No priority is set
  • 19. Quiz Contd.. 3.Which is NOT a thread priority related method ? 1. setPriority () 2. setPriorities() 3. yield() 4. getPriority() 19
  • 20. Quiz 4.If the thread priority is higher 1. Less chance for it to get executed first 2. Greater chance for it to get executed first 3. Equal chance for it to get executed first 4. No chance for it to get executed first
  • 21. Assignments • Write Java programs to create two threads, one printing odd numbers and the other printing even numbers • Set the priority as MAX_PRIORITY - 2 for the first thread and MIN_PRIORITY + 3 for the second thread • Write an application in Java to test the two threads 21