×

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling.

Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other Runnable threads.  At any time when multiple threads are ready to be executed, the runtime system chooses for execution those Runnable threads that have the highest priority. The selected thread runs until a higher priority thread becomes runnable, it yields, or its run method exists, or its time-slicing which is given to that thread has been expired.

If the time-slicing of a given thread is finished or the highest priority thread comes in the Runnable state as compared to the previous higher priority thread, which is still running. This current running thread will be pre-empted from the Running state, and this highest priority thread will get time slice for completing its task in the Running state.  This type of scheduling is called Preemptive-priority scheduling.

First come First serve Scheduling: JVM, according to the arrival time of the thread, give the time slice for its execution and schedules the job of those threads according to its arrival time. In the ready queue, which job comes first, will get the CPU first. The lesser(fewer) the arrival time of the job, the sooner will the job gets the CPU.

Time-slicing scheduling: This is the preemptive version of first-come-first-serve scheduling. In this algorithm, every thread gets executed cyclically. A specific time slice is defined in the system, which is called time quantum. Each thread present in the ready queue is assigned time quantum of the CPU. If the execution of the process is completed during that time, then the thread will terminate else the thread will go back to the ready queue and waits for the next turn to complete the execution. Then the next new thread gets time slice for the execution in the processor.

Diagram of the Thread Scheduler:

Thread Scheduler in java

Working of the Thread Scheduler:

  1. There are four different threads created with different priorities in the operating system. i.e., Thread1, Thread2, Thread3, Thread4.
  2. Which thread goes first to the processor for execution, which is decided by the thread scheduler. Thread scheduler is the part of the JVM.
  3. Thread scheduler waiting for threads, which is come in some priorities (priority is the number between of 1 to 10 given by the JVM to thread). The higher priority thread is given to the processor immediately by the scheduler for the execution. When the further thread comes with the highest priority, the previously higher executing thread in the processor will be pre-empted from the processor, and this highest priority thread is given to the processor for completing its task. This type of algorithm is called preemptive-priority scheduling.
  4. If two threads come with the same priorities (Thread2 and Thread4), FCFS scheduling given to the threads for the execution in the processor by the thread scheduler, the first-come thread is given the time-slicing for its execution then this thread will be preempted from the processor after completing its time slice. Then there will be given the chance of execution to the other threads, or no blocking of the other threads otherwise leads to the starvation of the threads.

  There are three static variables defined in Thread class for priority which effect on the thread scheduler:

Method Description
  public static int MIN_PRIORITY This is minimum priority of the thread. value for this is 1.
  public static int NORM_PRIORITY This is default priority of a thread if do not explicitly define it. value for this is 5.
 public  static int MAX_PRIORITY This is maximum priority of a thread. Value for this is 10.

      Getting and setting method of the Thread Priority:

Method Description
 public final int getPriority() This method returns priority of given thread.
 public final void setPriority(int  p) This method changes the priority of thread to the value p.

     The methods which are affected by the priorities:

  1. yield():It gives a clue to the thread scheduler that it is ready to pause the execution when the yield() method is being called on the thread. The thread scheduler checks if there is any thread with the same or high priority than the current thread on which yield() method has called. If the scheduler finds any thread with the higher or same priority, then it will move the current thread to Ready/Runnable state and give processor to other thread, and if not, the current thread will keep executing.
  2.  sleep(): This method indicates the currently executing thread to sleep for the specified number of milliseconds so that another thread having time slice goes for the execution in the processor.
  3.  join(): This method is used to queue up a thread in execution. Once called on the thread, the current thread will wait till the calling thread completes its execution.

Example1: To set the priorities of the threads using the setPriority() method:

Example:

class A extends Thread
{
int i=0;
public void run()
{
System.out.println("Thread A started");
while(i<4)
{
System.out.println("\t value of i in Thread A:"+i);
i++;                
}                      
System.out.println("ThreadA finished");       
}
}
class B extends Thread
{
public void run()
{int i=0;
System.out.println("ThreadB started");
while(i<4)
{
System.out.println("\t value of i in Thread B:"+i);   
i++;
}
System.out.println("ThreadB finished");
}
}
class C extends Thread
{
public void run()
{
int i=0;
System.out.println("ThreadC started");
while(i<4)
{
System.out.println("\t value of i in Thread C"+i);
i++;
}
System.out.println("ThreadC finished");
}
}
public class scheduller {
public static void main(String[] args) {            
System.out.println("Main Thread started");             
A a=new A();
B b=new B();
C c=new C();
Thread th=Thread.currentThread();
System.out.println(th.getName());
th.setPriority(Thread.MAX_PRIORITY);
b.setPriority(Thread.MIN_PRIORITY);
c.setPriority(Thread.NORM_PRIORITY);
a.start();
b.start();
c.start();
}
} 

Output:

Thread Scheduler in java2

Explanation:

1. There are four threads in the above program.  ThreadA, ThreadB, ThreadC, and the main thread.

2. We are going to set the priorities of these threads using the Thread class non-static method setPriority.

3. In the setPriority method, we will use the static constant variables of the priority so that each thread got the priority according to the user

4. Then we are using the start method for executing the run method of the different threads.

5. As the main thread has MAX_PRIORITY, so thread scheduler provides first time slice to it to complete its execution.

6. As the ThreadC has NORM_PRIORITY, so next thread scheduler provides time slice to it to complete its execution.

7. The ThreadA has default NORM_PRIORITY, which is provided by the JVM. Both ThreadC and ThreadA have equal priorities, so FCFS time-slicing priorities have been given to the threads.

8. Then the ThreadB has MIN_PRIORITY, so the thread scheduler provides last time slice to it to complete its job.

9. As the run method of the respective threads completes, its execution also terminates.

Example 2: Effect on the join() method by using the priorities:

Case A: To show the output of the three threads having the join() methods without using priorities:

class A extends Thread
{
int i=0;
public void run()
{
System.out.println("Thread A started");
while(i<4)
{
System.out.println("\t value of i in Thread A:"+i);
i++;                
}                      
System.out.println("ThreadA finished");       
}
}
class B extends Thread
{
public void run()
{int i=0;
System.out.println("Thread B started");
while(i<4)
{
System.out.println("\t value of i in Thread B:"+i);   
i++;
}
System.out.println("ThreadB finished");
}
}
class C extends Thread
{
public void run()
{
int i=0;
System.out.println("Thread C started");
while(i<4)
{
System.out.println("\t value of i in Thread C"+i);
i++;
}
System.out.println("Thread C finished");
}
}
public class priority {
public static void main(String[] args) {            
System.out.println("Main Thread started");             
A a=new A();
B b=new B();
C c=new C();
a.start();
b.start();
c.start();
try
{
a.join();
b.join();
c.join();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
} 

Output:

Thread Scheduler in java3

Explanation:

1. ThreadA, ThreadB and ThreadC and the main thread have been created.

2. As first of all, join method call on ThreadA then on ThreadB and in last on ThreadC.

3. TheadB and ThreadC have to wait for ThreadA to complete its run method (execution of the thread).

4. ThreadC also waits for ThreadB to complete its execution so that it can start its job, which is assigned to it.

5. In last main thread is executed when all the user threads (ThreadA, ThreadB ThreadC) have finished their execution.

Case B: Effect of using the priorities in the above join() method  programs:

class A extends Thread
{
int i=0;
public void run()
{
System.out.println("Thread A started");
while(i<4)
{
System.out.println("\t value of i in Thread A:"+i);
i++;                
}                      
System.out.println("ThreadA finished");       
}
}
class B extends Thread
{
public void run()
{int i=0;
System.out.println("Thread B started");
while(i<4)
{
System.out.println("\t value of i in Thread B:"+i);   
i++;
}
System.out.println("ThreadB finished");
}
}
class C extends Thread
{
public void run()
{
int i=0;
System.out.println("Thread C started");
while(i<4)
{
System.out.println("\t value of i in Thread C"+i);
i++;
}
System.out.println("Thread C finished");
}
}
public class scheduller {
public static void main(String[] args) {            
System.out.println("Main Thread started");             
A a=new A();
B b=new B();
C c=new C();
b.setPriority(Thread.MAX_PRIORITY);
c.setPriority(Thread.NORM_PRIORITY);
a.setPriority(Thread.MIN_PRIORITY);
a.start();
b.start();
c.start();
try
{
a.join();
b.join();
c.join();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
} 

Output:

Thread Scheduler in java4

Explanation:

1. We have set the priorities of the threads in the above program.

2. ThreadB has MAX_PRIORITY, so thread scheduler gives first time slice to the ThreadB according to the maximum priorities.

3. ThreadC has NORM_PRIORITY, and ThreadA has MIN_PRIORITY, so the time slice has been given to the ThreadC  before the ThreadA.

4. The activity of the join method will follow to each thread after watching its priorities.

Example 3: Effect of priorities on the yield() method

Case A: Program having only the yield() method.

import
java.lang.*;
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
System.out.println(Thread.currentThread().getName());
}
}
public class priorityyield {
public static void main(String s[])
{
MyThread t=new MyThread();
t.start();
for(int i=0;i<5;i++)
{
MyThread.yield();
System.out.println(Thread.currentThread().getName());
 }
}          
} 

Output:

Thread Scheduler in java5

Explanation:

1. There are two threads Thread-0, and the main thread is created.

2. The Thread.yield() call in the main thread stack so it will be pre-empted from the Running state and send to the Runnable state.

3.Then next thread-0 (user thread) has taken time slice to complete its job.

4.when the main thread will get the time slice again then it will complete its remaining task

Case B: Effect of using the priority on the yield() method  program:

import java.lang.*;
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
System.out.println(Thread.currentThread().getName());
}
}
public class priorityyield {
public static void main(String s[])
{
MyThread t=new MyThread();
t.start();
t.setPriority(Thread.MIN_PRIORITY);
for(int i=0;i<5;i++)
{
MyThread.yield();
System.out.println(Thread.currentThread().getName());
 }
}                                                  
}                                                   

Output:

Thread Scheduler in java6

Explanation:

1. The main thread has a higher priority than the thread-0, so the main thread takes time slice before the thread-0.

2. The yield() method will work according to the priorities given to the threads here.

Example 4: Effect of priority on the sleep():

Case A: Program having the only sleep() method.

import java.lang.*;
public class ThreadDemo implements Runnable
{
Thread t;
public void run()
{
for(int i=0;i<4;i++)
{
System.out.println(Thread.currentThread().getName()+" "+i);
try
{
Thread.sleep(10);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public static void main(String[] s1)throws Exception {
Thread t1=new Thread(new ThreadDemo());
Thread tmain=Thread.currentThread();
t1.start();
t1.setName("ThreadA");
Thread t2=new Thread(new ThreadDemo());
t2.setName("ThreadB");
t2.start();
System.out.println(tmain.getName());
}
} 

Output:

Thread Scheduler in java7

Explanation:

1. There are the main thread, Thread-0, Thread-1 threads in the above program.

2. Thread-0 and Thread-1 are the threads on which Thread.sleep(10) will be called in the program.

3. As one thread goes to the sleeping state, then the next thread will get the time slice from the thread scheduler and execute its job.

4.when the thread will be sleeping, its time slice will be diminished, and new time slice is being given to the next runnable thread.

Case B: Program having the effect of the priority on the sleep() method.

import java.lang.*;
public class ThreadDemo implements Runnable
{
Thread t;
public void run()
{
for(int i=0;i<4;i++)
{
System.out.println(Thread.currentThread().getName()+" "+i);
try
{
Thread.sleep(10);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public static void main(String[] s1)throws Exception {
Thread t1=new Thread(new ThreadDemo());
Thread tmain=Thread.currentThread();
t1.start();
t1.setName("MIN Thread");
t1.setPriority(Thread.MIN_PRIORITY);
Thread t2=new Thread(new ThreadDemo());
t2.setName("NORM Thread");
t2.start();
t2.setPriority(Thread.NORM_PRIORITY);
System.out.println(tmain.getName());
tmain.setPriority(Thread.MAX_PRIORITY);
}
} 

Output:

Thread Scheduler in java8

Explanation:

1.As the main thread has MAX_PRIORITY. The first time slice will be given to it

2. Thread t2 has NORM_PRIORITY, so it will get time slice next.

3. Thread t1 has MIN_PRIORITY, so it will get the last time slice of the thread scheduler.

4. The thread will be affected by the sleep method. The thread goes to the sleep state then the time slice will be preempted by other threads.


Related Topics

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.

Packages in Java

Packages in Java can be defined as an assortment for grouping various classes and interfaces based on their performance. It is a catalog for holding various java files. They provide...

4 minutes read.

System Class in Java

The System class provides features including a way to load files and libraries, standard input, standard output, and errors throughput streams, accessibility to outside defined characteristics and environment variables, and...

3 minutes read.

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

3 minutes read.

Java Binary to Hexadecimal

Converting between types in programming is an important task. Moving from one kind to another kind conversion is occasionally necessary. We have discussed numerous conversion types in the section on...

3 minutes read.

Java Binary Operators

In this article, we are going to discuss about the binary operators in Java and their operations. Also, an example program will be discussed along with the operations. These are...

6 minutes read.

Checked vs Unchecked Exceptions in Java

In this tutorial, we will discuss Java's checked and unchecked Exceptions. Exception An exception is an undesirable event that disrupts the normal flow of the program. An exception is thrown at runtime. It...

4 minutes read.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 minutes read.

How to Convert String to char in Java

How to Convert String to char in Java There are two methods to convert String to char are: Using charAt() method Using tocharArray() method Using charAt() method This is the method of String class that...

3 minutes read.

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

Java Map Example

In Java, the Map is an interface that is used mainly to denote key and value pairs. The central concept and theme of this mapping in the java collection framework...

4 minutes read.

Sorting Program in Java

Sorting Program in Java: The sorting program in Java is used to sort arrays either in ascending or descending order.  There are two predefined methods available in Java that are...

6 minutes read.

Permutation Coefficient in Java

In this tutorial, we will get familiar with the permutation coefficient in Java.  We will understand it through examples and see different approaches to solving the problem. A permutation is a...

5 minutes read.

String Pool in Java

String Pool in Java: String is one of the most important discussed topics in Java. There are a lot of concepts related to the String and one of them is...

5 minutes read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.

Brilliant Number in Java

It is a number N that is made up of two prime numbers that have the same number of digits and is called a brilliant number. Several/Some of the brilliant Numbers...

3 minutes read.

Java Math hypot() Method

The hypot() method of Math class returns the square root for the expression x2 + y2 without the intermediate underflow or overflow . Syntax: public static double hypot(double x, double y) Parameters: The parameters...

2 minutes read.