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:

Working of the Thread Scheduler:
- There are four different threads created with different priorities in the operating system. i.e., Thread1, Thread2, Thread3, Thread4.
- Which thread goes first to the processor for execution, which is decided by the thread scheduler. Thread scheduler is the part of the JVM.
- 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.
- 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:
- 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.
- 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.
- 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:

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:

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:

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:

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:

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:

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:

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.