Skip to main content

Thread priority in java with example

Thread priority is useful to maintain threads in an order in java. When multiple threads are created and started, a 'Thread Scheduler' program will load all threads into JVM memory and executes them based on thread priority. This scheduler will allot more JVM time to those threads which are having higher priorities.
          The priority number of a thread will change from 1 to 10. The minimum priority (Thread.MIN_PRIORITY) of a thread is 1, and the maximum priority (Thread.MAX_PRIORITY) is 10. The normal priority of a thread (Thread.NORM_PRIORITY) is 5.

Example: Let us write a program to understand the thread priority. The thread with higher priority number will complete its execution first.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.javatbrains.threads;

class ThreadPriority extends Thread {
     int count = 0;

     public void run() {
          for (int i = 0; i < 10000; i++)
              count++;// count numbers up to 10000
          // Display which thread has completed counting and its priority
          System.out.println("Completed Thread: "
                   + Thread.currentThread().getName());
          System.out.println("Its Priority: "
                   + Thread.currentThread().getPriority());
     }
}

public class Priority {

     public static void main(String[] args) {
          ThreadPriority prior = new ThreadPriority();
          //Create two threads
          Thread t1 = new Thread(prior, "First");
          Thread t2 = new Thread(prior, "Second");
          //Set priorities for them
          t1.setPriority(Thread.MIN_PRIORITY);
          t2.setPriority(Thread.MAX_PRIORITY);
          //start first t1 and then t2
          t1.start();
          t2.start();
     }

}
OutPut:
     Completed Thread: Second
     Its Priority: 10
     Completed Thread: First
     Its Priority: 1

Daemon Thread:
          A daemon thread is a thread that executes continuously. Daemon threads are service providers for other threads or objects. It generally provides a background processing.
              •  To make a thread t as a daemon thread, we can use setDaemon() method as,
1
t.setDaemon(true);

              • To know if a thread is daemon or not, isDaemon() is useful.
1
boolean x = t2.isDaemon();

Animation Application Using Thread
          Let us see the use of the thread in animation application, where an object, an image or some text is moved from one place to another on the screen Here is an example program to see a moving banner using a thread. The logic is to extract the first character from a banner string and add it at the end of the string.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.javatbrains.threads;

import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;

public class Banner extends Frame implements Runnable{
     //This is the banner String
     String str = "JAVATBRAINS.BLOGSPOT.IN";
    
     public Banner(){
          setLayout(null);
          setBackground(Color.CYAN);
          setForeground(Color.RED);
     }
    
     public void paint(Graphics g){
          //Set a font and display the banner string
          Font f = new Font("times new roman", Font.BOLD, 40);
          g.setFont(f);
          g.drawString(str, 10, 100);
     }
    
     @Override
     public void run() {
          for(;;){  //Move banner continuously
              repaint();    //Refresh the frame contents
              try{
                   Thread.sleep(1000);     //Give a gap of each movement
              }catch(InterruptedException ie){
                   ie.printStackTrace();
              }
             
              char ch = str.charAt(0);
              str = str.substring(1,str.length());
              str = str+ch; //attach the first character at the end of str
             
          }
     }
    
     public static void main(String[] args) {
          Banner b = new Banner();
          b.setSize(670, 150);
          b.setTitle("BLOGSPOT.COM");
          b.setVisible(true);
          //create a thread and run it
          Thread t = new Thread(b);
          t.start();
     }
}

About GREEN and NATIVE threads:
Both the threads are mechanism support to multithread execution of Java program.

Green Thread:
          Green Threads are threads are scheduled by a JVM. Green is earlier JVM project code name. It is name of library which is provided VM-scheduled threads in Java-1.1. Green threads refers to a model in which the JVM itself creates, manages and context switches all java threads with in one operating system process. No operating system threads library is used. Green threads are in past, JVM's will work only with native threads since JDK 1.3.

Native Threads:
          Native threads are scheduled by an operating system. Native thread called so because they are belong to native platform. Native thread refers to a in which JVM creates and manages. Java thread using the operating system thread library – named lib thread on UnixWare – and each Java thread is mapped to one threads library thread.

Do you know?


  • User defined threads in java with example 
  • Thread priority in java with example
  • Comments

    Popular posts from this blog

    Multithreading in java with example

    Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...

    JNDI configuration for Tomcat 9 with Oracle

    In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...

    Git installation for AngularJS 2 in Windows 10

    Download Git latest version from https://git-scm.com/downloads or you click on the below link to download directly for windows https://git-scm.com/download/win . Once download completes, click on executable file to start installation process and choose Yes to allow the software installation in windows 10. Click on Next button to continue further installation. Browse the isntallation directory and click on Next button to continue. Select the list of components which you want to be installed and click on Next button to proced further installation. Type the shortcut name for Start menu and click on Next button. Select how you want to use the Git and click on Next button. For Windows no need to change anything, let it be the default one. Choose the Use the OpenSSL library and click on Next button. Select how should Git treat line ending in text files and click on Next button. Select which terminal emulator to use with Git and click on Next button. Configure extr...