×

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

All the important string methods in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Integer floatValue() method

The floatValue() method of Integer class returns a float value for this Integer after a widening primitive conversion. Syntax public float floatValue() Parameters NA Specified by This method is specified by floatValue in class Number Return Value This...

1 minute read.

Bedrock vs Java

The popularity of Minecraft, a sandbox video game, has skyrocketed. The scope, level of complexity, and variety of gameplay in this game are enormous, and user-generated content has helped to...

4 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a...

5 minutes read.

Best Java Libraries

One of the most widely used programming languages is Java. Java has a large number of libraries, including the standard Java library that includes libraries such as java.lang, java.util, and...

7 minutes read.

Tug of War in Java

As in the tug-of-war issue, we must divide the given collection of n numbers into two groups of sizes that are equal or nearly equivalent. A minimum difference must exist...

5 minutes read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.

Program to find the duplicate characters in a string

Problem statement You have given with a string and your task is to find out the repeated characters from the string and print them. If no character is repeated, then you...

2 minutes read.

How to Create an API in Java?

Introduction The API can be abbreviated as Application Programming Interface. An API is a combination of set of classes and interfaces. It is also equivalent to a simple java program. To...

12 minutes read.

Package Program in Java

Package Program in Java The package program in Java helps us to understand the significance of packages in Java. Packages are mainly used to group together similar classes, interfaces and sub-packages....

6 minutes read.

Set Value to Enum in Java

In this article, you will be acknowledged about Enum in java. Most importantly you will learn how to set value to Enum or how to practically customize a value to...

3 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

Java Math addExact() Method

The addExact() method of Math class returns the sum of the two arguments, throwing an exception if the result overflows a long or an int. Syntax public static int addExact (int x,...

1 minute read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

4 minutes read.

Reverse a String in Java

Reversing a string means that if we have a string called “what is your name”, the reversed format is “eman ruoy si tahw”. Reversing a string involves totally flipping the...

3 minutes read.

Bottom view of a binary tree in Java

The lowest nodes in their horizontal distance are present and referred to as the bottom view of a binary tree. The horizontal distance between the nodes of a binary tree...

4 minutes read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Java URL Class with Example

Java URL Uniform Resource Locator To find any resource on the internet, you need to have an address of it. The URL and IP addresses are the pointers used for this purpose....

12 minutes read.