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

    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...

    Prime, Fibonacci and Factorial number with example in java

    Prime number, Fibonacci series and Factorial number programs are most commonly asked questions in interview. Read this article to know what is and how to write programs for prime number, fibonacci series and factorial number. Prime Number: prime number is natural number greater than 1 that has no positive divisor other than 1 and itself. A natural number greater than 1 is not a prime number, is called Composite number . For example, 7 is a prime number. Because it can divide with 1 and 7 only. Where as 8 is composite number. Since it has the divisor 2 and 4 in addition to the 1 and 8. The below example represents the finding the passing number is prime number or not. If the passing number is prime number it will print true otherwise it will print false. package com . javatbrains . practice ; public class PrimeNumber { public boolean isPrimeNumber ( int number ) { if ( number <= 1 ) return false ; // There's only one ...

    JVM, JRE and JDK in Java

    JVM, JRE and JDK are the most basic common concepts to know in java. These are the basic features to understand how Java architecture works? JVM stands for Java Virtual Machine, which doesn't have any physical directories created in java installation. JRE stands for Java Runtime Environment, which creates the directory under Java installation path and also present in JDK. JDK stands for Java Development Kit, which creates the directory in Java installation path and also it has it's own JRE. Since we have already learn that Java is platform independent means if we have implemented any of the java class in one environment, it will be executed in any other environment and provides the same output. But, JVM, JRE and JDK all are platform dependent . So that, for windows, linux, unix, mac, solaris..etc has it's own JVM, JRE and JDK. One will be not compatible with other environments. While installing the Java, we might come to know a bit about JRE and JDK. But, JVM is the other...