Java Tutorial

Java Tutorial Java Features C++ vs Java Java History Java Hello World Java Development Kit Java Runtime Environment Java Virtual Machine Difference between JDK, JRE, and JVM Memory Areas in Java Java Operators Java Keywords Primitive Data Types Variables

Java Loops

Java Do While Loop Java While Loop Java For Loop Java Enhanced For Loop

Java Programs

Java Basic Programs Factorial Program in Java Fibonacci Series Program in Java Prime Number Program in Java Palindrome Number Program in Java Armstrong Number Program in Java Anagram Program in Java Pattern Programs in Java Calculator Program in Java Leap Year Program in Java Addition Program in Java Number Pattern Programs in Java Star Pattern Programs in Java Package Program in Java Pyramid Program in Java Sorting Program in Java String Palindrome Program in Java Even Odd Program in Java For Loop Program in Java If Else Program in Java Switch Case Program in Java GCD Program in Java LCM Program in Java Hello Program in Java Matrix Program in Java Menu Driven Program in Java Series Program in Java Client Server Program in Java Swapping Program in Java Pig Latin Program in Java Tower of Hanoi Program in Java Recursion Program in Java Matrix Multiplication Program in Java Perfect Number Program in Java Classes and Objects in Java Example Programs String Programs in Java Array Programs in Java Constructor Program in Java Inheritance Program in Java Abstract class Program in Java Interface Program in Java Encapsulation Program in Java Polymorphism Program in Java Exception Handling Program in Java Multithreading Program in Java Thread Program in Java Collection Programs in Java ArrayList Program in Java Stack Program in Java Applet Program in Java Swing Program in Java JDBC Program in Java How to run Java program in command prompt How to run Java program in Eclipse

Java Sorting

Sorting Algorithms in Java Merge Sort in Java Quick Sort in Java Bubble Sort in Java Insertion Sort in Java Selection Sort in Java Heap Sort in Java Radix Sort in Java Topological Sort in Java Bucket Sort in Java Counting Sort in Java

Java OOPs Concepts

OOPs - Object Oriented Programming Objects and Classes in Java Java Naming Conventions Constructors in Java Java this keyword Java static keyword Inheritance in Java Aggregation in Java Java super keyword Constructor Chaining and Constructor Overloading Java Polymorphism Static and Dynamic Binding in Java Java Abstraction Abstract class in Java Interface in Java Difference between Abstract class and Interface Java final keyword Packages in Java Access Modifiers in Java Java Wrapper classes Java Numbers Java Characters Java Integer Java Boolean Java Arrays Java Command Line Arguments Java strictfp Keyword Java Math

Java Strings

Java Strings Java String Methods StringBuilder in Java StringBuffer in Java Java Regular Expressions StringBuffer vs StringBuilder String vs StringBuffer String vs StringBuilder String Manipulation in Java Java String Concatenation How to Reverse a String in Java String Array in Java How to Compare Two Strings in Java How to Concatenate Two Strings in Java Why String in Immutable in Java java.lang.NumberFormatException for Input String String Pool in Java Java Generate Random String How to take String Input in Java Java String Interview Questions

Java Exceptions

Exception Handling in Java Java try catch Java throw Java throws Difference between throw and throws Java finally Java Custom Exception Java Exception Propagation

Garbage Collection

Automatic Resource Management in Java Java Garbage Collection Java finalize() Java gc() Difference between final, finally and finalize

Multithreading

Multithreading in Java Process and Thread in Java Basic Terms in Multithreading Java Thread creation Thread Scheduler in Java Java Thread class DeadLock in Java

Java IO

Java IO Java Read File Java BufferedWriter Java InputStreamReader Java File Java Read File Line By Line Java FileOutputStream Jar File in Java

Serialization

Java Serialization Java transient

Networking

Java Network Programming Java Socket Programming Java URL Java URLConnection HttpURLConnection in Java Java InetAddress Java DatagramSocket and Java DatagramPacket

AWT

Java AWT

Swing

Swing in Java

Java Collections

Collections in Java Java List Interface ArrayList in Java LinkedList in Java Vector in Java Stack in Java ArrayList vs LinkedList in Java ArrayList vs Vector in Java Java Set Interface HashSet in Java LinkedHashSet in Java TreeSet in Java Java Queue Interface PriorityQueue in Java ArrayDeque in Java Java Map Interface HashMap in Java LinkedHashMap in Java TreeMap in Java Dictionary in Java Hashtable in Java Properties in Java Collections class in Java Java Comparable Java Comparator Comparable vs Comparator in Java

Java Generics

Generics in Java

Java Annotations

Annotations in Java

Java JDBC

Java JDBC Tutorial

Java Differences

Java vs JavaScript Python vs Java Kotlin vs Java Java vs C++ C# vs Java Static vs Non-static in Java C vs Java int vs Integer in Java Stack vs Heap in Java Java Array vs ArrayList

How to

How to run Java program How to set path in Java How to check the Java version in cmd How to install Java in Windows 10 How to run Java program in cmd How to call a method in Java How to sort an array in Java How to iterate HashMap in Java How to write Java program How to create an array in Java How to create a package in Java How to generate random numbers in Java How to input String in Java How to create thread in Java How to find length of String in Java How to sort a string in Java How to use scanner in Java How to achieve multiple inheritance in Java How to run Java program in Eclipse How to call a function in Java How to create array of objects in Java How to create custom exception in Java How to achieve abstraction in Java How to call static method in Java

Java 8 Features

Java 8 Features Lambda Expressions in Java Functional Interface in Java Streams in Java Java Base64 Encoding and Decoding Parallel Arrays Sort in Java

Java 9 Features

Java 9 Tutorial Java 9 Try With Resources Java 9 Interface Private Method

Java Servlet Tutorial

Java Servlets Tutorial

Java JSP Tutorial

Java JSP Tutorial

Hibernate Tutorial

Hibernate Tutorial

Spring Tutorial

Spring Tutorial

Spring MVC Tutorial

Spring MVC Tutorial

Jenkins Tutorial

Jenkins Tutorial

Java Math Methods

Math.abs() Math.acos() Math.addExact() Math.asin() Math.atan () Math.atan2() Math.cbrt() Math.ceil() Math.copysign() Math.cos() Math.cosh() Math.decrementExact() Math.exp() Math.expm1() Math.floor() Math.floorDiv() Math.floorMod() Math.getExponent() Math.hypot() Math.IEEEremainder() Math.incrementExact() Math.log() Math.log10() Math.log1p() Math.max() Math.min() Math.multiplyExact() Math.multiplyFull() Math.negateExact() Math.nextAfter() Math.nextDown() Math.nextUp() Math.pow() Math.random() Math.rint() Math.round() Math.scalb() Math.signum() Math.sin() Math.sinh() Math.sqrt() Math.subtractExact() Math.tan() Math.tanh() Math.toDegrees() Math.toIntExact() Math.toRadians() Math.ulp()

Java String Methods

toCharArray() copyValueOf() endsWith() equals() equalsIgnoreCase() format() getBytes() getChars() hashCode() indexOf() intern() isEmpty() join() lastIndexOf() length() replace() replaceAll() replaceFirst() split() startsWith() subSequence() substring() toLowerCase() toUpperCase() trim() valueOf()

Java Conversion

Java Convert String to int Java Convert int to String Java Convert String to long Java Convert long to String Java Convert String to float Java Convert float to String Java Convert String to double Java Convert double to String Java Convert String to Date Java Convert Date to String Java Convert String to Object Java Convert Object to String Java Convert String to char Java Convert char to String Java Convert int to long Java Convert long to int

Misc

Functional Interfaces in Java Singleton class in Java Awesome explanation of Strings in Java Object class in Java Static class in Java All the important string methods in Java String Handling Method in Java What are Array strings in Java Advantages and Disadvantages of Strings in Java Big Decimal class in Java Class definition in Java Char and String differences in Java Difference between String, StringBuffer and StringBuilder in java Replace character in string Java String Coding Interview Questions in Java What is String in Java? String isnullorempty in Java String Matches in Java Trim Method in String Java Bean class in Java Libraries in Java Arithmetic Operations on String in Java Convert Char array to string in java Check whether Java is installed or not How to calculate time difference in Java How to stop execution after a certain time in Java Jagged Array in Java Java ArraylistRemove() Time Complexity Java Swing Time Picker Zigzag Array in Java

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.



ADVERTISEMENT
ADVERTISEMENT