Life cycle of thread in java

  • Its recommended to learn about life cycle of Thread before you start programming on Thread.
  • Threads exists in different type of states.

  • Thread having below states.
  1. New State
  2. Ready State
  3. Running State
  4. Dead State
  5. Non Runnable States 

Life cycle of thread in java with diagram
Life cycle of a Thread

1.New State:

  • A thread has been created but not started yet. A thread will be started by calling its start() method.

2.Runnable State:

  • This state is also called ready to run stage also called queue. A thread starts in runnable state by calling start() method.
  • The Thread scheduler decides which thread runs and how long.

3.Running State:

  • If a Thread is executing that means Thread is in Running stage.

4.Dead State:

  • Once a Thread reached dead state it can not run again.


5. Non runnable States:

  • A Running Thread transit to one of the non runnable states, depending upon the circumstances.
  • A Thread remains non runnable until a special transition occurs.
  • A Thread does not go directly to the running state from non runnable state.
  • But transits first to runnable state.
  1. Sleeping: The Threas sleeps for specified amount of time.
  2. Blocked for I/O: The Thread waits for a blocking operation to complete.
  3. Blocked for join completion: The Thread waits for completion of another Thread.
  4. Waiting for notification: The Thread waits for notification another Thread.
  5. Blocked for lock acquisition: The Thread waits to acquire the lock of an object.
  • JVM executes the Thread based on their priority and scheduling.

Thread Scheduler:

  • Schedulers in JVM implementations usually employ one of these two Strategies.
  • Preemptive Scheduling
  • Time Sliced or Round robin Scheduling
  • Thread schedulers are implementation and platform independent, therefore how thread will scheduled is unpredictable

Thread priority:

  • JVM will assign a priority for every Thread created in it.
  • 0- will be the minimum priority
  • 5- will be the normal priority
  • 10- will be the maximum priority
  • To hold all these values Thread class has below three corresponding variables
  • public static final int MIN_PRIORITY
  • public static final int NORM_PRIORITY
  • public static final int MAX_PRIORITY 
  •  A thread inherits the priority of its parent Thread. The default priority of the every thread is normal priority 5, because main thread priority is 5.
  • We can set the priority of a thread by using setPriority(int priority) method
  • public final void setPriority(int priority)
  • public void getPriority();
  • User defined thread created with default name  Thread+<index>, where index is the integer number starts from 0.
  • The name of a thread can be change using setName(String name) method.
  • Get by using getName() method.
  • public final void setName(String name)
  • public final String getName().



Life cycle of thread in java program
  1. package com.instanceofjava;
  2.  
  3. class UserThread{
  4.      
  5. UserThread(){
  6.         super();
  7.  }
  8.  
  9.  UserThread(String name){
  10.         UserThread(name);        
  11.  }
  12.  
  13.  public void run()
  14.  {
  15.       System.out.println("thread started running..");
  16.  }
  17.  
  18. public static void main(String [] args){ 

  19.   UserThread thread1 = new UserThread("Thread1");
  20.   UserThread thread2 = new UserThread("Thread2");        

  21.          System.out.println("Thread 1 initial name and priority");
  22.          System.out.println("name:"+thread1.getName());
  23.          System.out.println("priority:"+thread1.getPriority());
  24.  
  25.       System.out.println("Thread 2 initial name and priority");
  26.       System.out.println("name:"+thread2.getName());
  27.       System.out.println("priority:"+thread2.getPriority());
  28.  
  29.       thread1.setPriority(6);
  30.       thread2.setPriority(9);
  31.  
  32.       System.out.println("Thread 1 initial name and priority");
  33.       System.out.println("name:"+thread1.getName());
  34.       System.out.println("priority:"+thread1.getPriority())
  35.  
  36.       System.out.println("Thread 2 initial name and priority");
  37.       System.out.println("name:"+thread2.getName());
  38.       System.out.println("priority:"+thread2.getPriority());
  39.  
  40.       thread1.start();
  41.       thread2.start();
  42.  
  43.       for (int i = 0; i < 5; i++) {
  44.           System.out.println("main method i value:"+i);
  45.     }
  46. }
  47. }


Output:

  1. Thread 1 initial name and priority
  2. name:Thread1
  3. priority:5
  4. Thread 2 initial name and priority
  5. name:Thread2
  6. priority:5
  7. Thread 1 initial name and priority
  8. name:Thread1
  9. priority:6
  10. Thread 2 initial name and priority
  11. name:Thread2
  12. priority:9
  13. Thread1i:0
  14. Thread1i:1
  15. Thread1i:2
  16. Thread2i:0
  17. Thread1i:3
  18. Thread1i:4
  19. Thread2i:1
  20. Thread2i:2
  21. Thread2i:3
  22. Thread2i:4
  23. main method i value:0
  24. main method i value:1
  25. main method i value:2
  26. main method i value:3
  27. main method i value:4

Java programming interview questions

  1. Print prime numbers? 
  2. What happens if we place return statement in try catch blocks 
  3. Write a java program to convert binary to decimal 
  4. Java Program to convert Decimal to Binary
  5. Java program to restrict a class from creating not more than three objects
  6. Java basic interview programs on this keyword 
  7. Interfaces allows constructors? 
  8. Can we create static constructor in java 
  9. Super keyword interview questions java 
  10. Java interview questions on final keyword
  11. Can we create private constructor in java
  12. Java Program Find Second highest number in an integer array 
  13. Java interview programming questions on interfaces 
  14. Top 15 abstract class interview questions  
  15. Java interview Questions on main() method  
  16. Top 20 collection framework interview Questions
  17. Java Interview Program to find smallest and second smallest number in an array 
  18. Java Coding Interview programming Questions : Java Test on HashMap  
  19. Explain java data types with example programs 
  20. Constructor chaining in java with example programs 
  21. Swap two numbers without using third variable in java 
  22. Find sum of digits in java 
  23. How to create immutable class in java 
  24. AtomicInteger in java 
  25. Check Even or Odd without using modulus and division  
  26. String Reverse Without using String API 
  27. Find Biggest substring in between specified character
  28. Check string is palindrome or not?
  29. Reverse a number in java?
  30. Fibonacci series with Recursive?
  31. Fibonacci series without using Recursive?
  32. Sort the String using string API?
  33. Sort the String without using String API?
  34. what is the difference between method overloading and method overriding?
  35. How to find largest element in an array with index and value ?
  36. Sort integer array using bubble sort in java?
  37. Object Cloning in java example?
  38. Method Overriding in java?
  39. Program for create Singleton class?
  40. Print numbers in pyramid shape?
  41. Check armstrong number or not?
  42. Producer Consumer Problem?
  43. Remove duplicate elements from an array
  44. Convert Byte Array to String
  45. Print 1 to 10 without using loops
  46. Add 2 Matrices
  47. Multiply 2 Matrices
  48. How to Add elements to hash map and Display
  49. Sort ArrayList in descending order
  50. Sort Object Using Comparator
  51. Count Number of Occurrences of character in a String
  52. Can we Overload static methods in java
  53. Can we Override static methods in java 
  54. Can we call super class static methods from sub class 
  55. Explain return type in java 
  56. Can we call Sub class methods using super class object? 
  57. Can we Override private methods ? 
  58. Basic Programming Questions to Practice : Test your Skill
  59. Java programming interview questions on collections

Difference between throw and throws in java

throw keyword:
  • throw keyword used to throw user defined exceptions.(we can throw predefined exception too)
  • If we are having our own validations in our code we can use this throw keyword.
  • For Ex: BookNotFoundException, InvalidAgeException (user defined).

Program:
  1. package com.instanceofjava;
  2. public class MyExceptionThrow {
  3.  
  4.  public static void main(String a[]){
  5.  
  6.  try{
  7.  
  8. MyExceptionThrow thr = new MyExceptionThrow();
  9. System.out.println("length of INDU is "+thr.getStringSize("INDU"));
  10. System.out.println("length of SAIDESH is "+thr.getStringSize("SAIDSH"));
  11. System.out.println("length of null string is "+thr.getStringSize(null)); 
  12.  
  13.  }
  14. catch (Exception ex){
  15.   System.out.println("Exception message: "+ex.getMessage());  
  16.  }
  17.  }
  18.  
  19.  public int getStringSize(String str) throws Exception{
  20.  
  21.  if(str == null){
  22.    throw new Exception("String input is null");  
  23.  }
  24.  return str.length();
  25. }
  26.  
  27. }


Output
length of INDU is 4
length of SAIDESH is 5
Exception message: String input is null



 throws keyword:

  •  The functionality of throws keyword is only to explicitly to mention that the method is proven transfer un handled exceptions to the calling place.

Program:
  1. package com.instanceofjava;
  2. public class ExcpetionDemo {
  3.  
  4. public static void main(String agrs[]){
  5.  
  6. try
  7. {
  8. //statements
  9. }
  10. catch(Exception e)
  11. {
  12. System.out.println(e);
  13. }
  14. finally(){compulsorily executable statements
  15. }
  16. }
  17.  
  18. }

User Defined Exceptions in java

Apart from java we have Existing Exceptions. and we can also create our own Exceptions nothing but User defined Exceptions.
User defined exceptions in java are also known as Custom exceptions.

Program:
InvalidAgeException .java:
  1. package com.instanceofjava;
  2. class InvalidAgeException extends Exception{  
  3.  InvalidAgeException(String s){ 
  4. super(s);   
  5. }
  6. }  
Program:
TestUsrDefinedException,java:
  1. package com.instanceofjava;
  2. class TestUsrDefinedException{ 
  3.  static void validate(int age)throws InvalidAgeException{  
  4.  if(age<18)  
  5.   throw new InvalidAgeException("Invalid age");
  6.  else  
  7.  System.out.println("welcome to vote");  
  8. }  
  9. public static void main(String args[]){
  10.  try{  
  11.  validate(13);  
  12.  }
  13. catch(Exception m){
  14. System.out.println("Exception occured: "+m);
  15. }
  16. finally{
  17.  System.out.println("This block will be Executed")
  18. }
  19. }
  20. }   


try catch finally in java

try block:

  • The functionality of try keyword is to identify an exception object.
  • And catch that exception object and transfer the control along with the identified exception object to the catch block by suspending the execution of the try block.
  • All the statements which are proven to generate exceptions should be place in try block.
Syntax of try block:

try
{
//try block
//keep those statements which may
//throw run time exceptions
}

catch Block:
  •  The functionality of catch block is to receive the exception class object that has been send by the "try".
  • And catch that exception class object and assigns that exception class object to the reference of the corresponding exception class defined in the catch block.
  • And handle the exception that has been identified by "try".
  • "try"  block identifies an exception and catch block handles the identified exception.
Syntax:

catch(Exception e)
{
//catch block.
//one argument of type java.lang.Exception
//catches the exceptions thrown by try block
}

finally block:


  • finally blocks are the blocks which are going to get executed compulsorily irrespective of exceptions.
  • finally blocks are optional blocks.
Syntax:

finally
{
//This is the finally block.
}

Example Program:
  1. package com.instanceofjava;
  2. public class MyException {
  3.  
  4.  public static void main(String a[]){
  5.  
  6.   try{         
  7. int i = 10/0;             
  8.   System.out.println("This statement won't executed");      
  9.  } 
  10. catch(Exception ex){
  11.  
  12.   System.out.println("This block is executed immediately after an exception is thrown");
  13.  
  14.   }
  15.  finally{
  16. System.out.println("This block is always executed");}
  17.  }
  18.  
  19. }
Output:
  1. This block is executed immediately after an exception is thrown
  2. This block is always executed.

Different Ways to Create Thread in Java

  • In  java we can create user defined threads in two ways 
  1. Implementing Runnable interface
  2. extending Thread class.

  • These are the two different ways to create thread in java
  • In these two ways first step we need to override run() method and place corresponding logic that should be executed concurrently.
  • The second thing is to call the start() method on Thread class object to create a thread of execution in Java Stack area.

1. Create thread in java using Runnable:

  • Simple and easiest way to create a thread is create a class that implements Runnable interface.
  • If you implement Runnable interface then our class instances will be executed by a thread.
  • Runnable interface having only one method called run().
  • After implementing the Runnable interface we need to override run() method of Runnable interface.
  1. public void run(){
  2. //logic
  3. }
  • This run(0 method introduces concurrent thread in to our program
  • The execution of thread will end when it reaches end of the run method.
  • run() method returns nothing.

  1. package com.instanceofjava;
  2.  
  3. class UserThread implements Runnable{
  4.  
  5.  public void run()
  6. {
  7.  
  8.  for (int i = 0; i < 5; i++) {
  9.       System.out.println(i);
  10.  
  11. }
  12. }
  13.  
  14. public static void main(String [] args){ 

  15.    
  16.       UserThread userth= new UserThread();
  17.  
  18.       Thread t = new Thread(userth);
  19.       t.start();
  20.  
  21. }
  22. }


Output:

  1. 0
  2. 1
  3. 2
  4. 3
  5. 4

 


2. Java extends thread example


  • The second way to create object in java is by extending Thread class
  • Thread class having constructors and methods to create Thread
  • Thread class extends Object class and implements Runnable interface.

  1. public class Thread
  2. extends Object
  3. implements Runnable 

  1. package com.instanceofjava;
  2.  
  3. class UserThread extends Thread{
  4.  
  5.  public void run()
  6.  {
  7.       System.out.println("thread started running..");
  8.  }
  9.  
  10. public static void main(String [] args){ 

  11.    
  12.       UserThread userth= new UserThread();
  13.  
  14.       Thread t = new Thread(userth);
  15.       t.start();
  16.  
  17. }
  18. }


Output:

  1. thread started running..




Thread class Constructors:

1.Thread()
  • Allocates a new Thread object.
2.Thread(Runnable target)
  • Allocates a new Thread object.
3.Thread(Runnable target, String name)
  • Allocates a new Thread object.
4.Thread(String name)
  • Allocates a new Thread object.
5.Thread(ThreadGroup group, Runnable target)
  • Allocates a new Thread object.
6.Thread(ThreadGroup group, Runnable target, String name)
  • Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group.

7.Thread(ThreadGroup group, Runnable target, String name, long stackSize)
  • Allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group, and has the specified stack size.

Thread Class Methods:

  1. public void run(): method used to perform action for a thread. it is the initial point of custom thread execution.
  2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
  3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
  4. public void join(): waits for a thread to die.
  5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
  6. public int getPriority(): returns the priority of the thread.
  7. public int setPriority(int priority): changes the priority of the thread.
  8. public boolean isAlive(): tests if the thread is alive.
  9. public void yield(): This method execution causes the currently executing thread object to temporarily pause and allow other threads to execute.
  10. public void suspend(): method will be used to suspend the thread(depricated method).
  11. public void resume(): method used to resume the suspended thread(depricated method).
  12. public void stop(): method used to stop the thread(depricated method).
  13. public boolean isDaemon(): tests if the thread is a daemon thread.
  14. public void setDaemon(boolean b): marks the thread as daemon or user thread.
  15. public void interrupt(): interrupts the thread.

Java Example program on extends thread

  1. package com.instanceofjava;
  2.  
  3. class UserThread extends Thread{
  4.  
  5.  public void run()
  6.  {
  7.       System.out.println("thread started running..");
  8.  }
  9.  
  10. public static void main(String [] args){ 

  11.    
  12.       UserThread userth= new UserThread();
  13.  
  14.       userth.start();
  15.  
  16. }
  17. }

Output:

  1. thread started running..

Top 20 Basic Java Interview Programs on Increment Decrement operators

  • In most of the interviews questions on increment and decrement operators will come in face to face or in written test.
  • Every Java Interview written test will have compulsory one question on increment and decrements operators.
  • Lets see some of the frequently asking java interview  programming questions on increment and decrement operators.
  • I this pre increment and post increment , pre decrement and post decrement topics will cover in below programs.
  • Normal programs: use of increment and decrement in normal scenario is same.
  • They differ in while we use them in expressions.
  • To avoid confusions for basic java learners we provided individual programs.

1.Java Interview program on pre increment operator.


  1. package com.instanceofjava;
  2.  
  3. class IncrementDemo{
  4.  
  5. public static void main(String [] args){ 

  6.     int a, b;
  7.      a=10;
  8.      b=++a;
  9.     System.out.println(b);
  10.  
  11. }
  12. }
Output:
  1. 11

2.Java Interview program on post increment operator.


  1. package com.instanceofjava;
  2.  
  3. class IncrementDemo{
  4.  
  5. public static void main(String [] args){ 

  6.     int a, b;
  7.      a=10;
  8.      b=a++;
  9.     System.out.println(a);
  10.  
  11. }
  12. }
Output:
  1. 11

3.Java Interview program on pre increment operator in expression.


  1. package com.instanceofjava;
  2.  
  3. class IncrementDemo{
  4.  
  5. public static void main(String [] args){ 

  6.     int a=20;
  7.     a= ++a + 1;
  8.  
  9.     System.out.println(a);
  10.  
  11. }
  12. }
Output:
  1. 22

4.Java Interview program on post increment operator in expression.


  1. package com.instanceofjava;
  2.  
  3. class IncrementDemo{
  4.  
  5. public static void main(String [] args){ 

  6.     int a=20;
  7.     a= a++ + 1;
  8.  
  9.     System.out.println(a);
  10.  
  11. }
  12. }
Output:
  1. 21

5.Java Interview program on pre increment operator in expression.


  1. package com.instanceofjava;
  2.  
  3. class IncrementDemo{
  4.  
  5. public static void main(String [] args){ 

  6.     int a=20;
  7.     a= ++a + ++a;
  8.  
  9.     System.out.println(a);
  10.  
  11. }
  12. }
Output:
  1. 43

6.Java Interview program on post increment operator in expression.


  1. package com.instanceofjava;
  2.  
  3. class IncrementDemo{
  4.  
  5. public static void main(String [] args){ 

  6.     int a=20;
  7.     a= a++ + a++;
  8.  
  9.     System.out.println(a);
  10.  
  11. }
  12. }
Output:
  1. 41

7.Java Interview program on pre and post increment operator in expression.


  1. package com.instanceofjava;
  2.  
  3. class IncrementDemo{
  4.  
  5. public static void main(String [] args){ 

  6.     int a=20;
  7.     a= a++ + ++a;
  8.  
  9.     System.out.println(a);
  10.  
  11. }
  12. }
Output:
  1. 42




8.Java Interview program on pre decrement


  1. package com.instanceofjava;
  2.  
  3. class IncrementDemo{
  4.  
  5. public static void main(String [] args){ 

  6.     int a, b;
  7.      a=10;
  8.      b=--a;
  9.     System.out.println(b);
  10.  
  11. }
  12. }
Output:
  1. 9

9.Java Interview program on post decrement .


  1. package com.instanceofjava;
  2.  
  3. class IncrementDemo{
  4.  
  5. public static void main(String [] args){ 

  6.     int a, b;
  7.      a=30;
  8.      b=a--;
  9.     System.out.println(a);
  10.  
  11. }
  12. }
Output:
  1. 29

10.Java Interview program on pre decrement in expression.


  1. package com.instanceofjava;
  2.  
  3. class IncrementDemo{
  4.  
  5. public static void main(String [] args){ 

  6.     int a=20;
  7.     a= --a - 1;
  8.  
  9.     System.out.println(a);
  10.  
  11. }
  12. }
Output:
  1. 18

11.Java Interview program on post decrement in expression.


  1. package com.instanceofjava;
  2.  
  3. class IncrementDemo{
  4.  
  5. public static void main(String [] args){ 

  6.     int a=20;
  7.     a= a-- - 1;
  8.  
  9.     System.out.println(a);
  10.  
  11. }
  12. }
Output:
  1. 19

12.Java Interview program on pre decrement in expression.


  1. package com.instanceofjava;
  2.  
  3. class IncrementDemo{
  4.  
  5. public static void main(String [] args){ 

  6.     int a=20;
  7.     a= --a - --a;
  8.  
  9.     System.out.println(a);
  10.  
  11. }
  12. }
Output:
  1. 1

13.Java Interview program on post decrement operator in expression.


  1. package com.instanceofjava;
  2.  
  3. class IncrementDemo{
  4.  
  5. public static void main(String [] args){ 

  6.     int a=20;
  7.     a= a-- - a--;
  8.  
  9.     System.out.println(a);
  10.  
  11. }
  12. }
Output:
  1. 1

14.Java Interview program on pre and post decrement operator in expression.


  1. package com.instanceofjava;
  2.  
  3. class IncrementDemo{
  4.  
  5. public static void main(String [] args){ 

  6.     int a=20;
  7.    a= a--  - --a;
  8.  
  9.     System.out.println(a);
  10.  
  11. }
  12. }
Output:
  1. 2

15.Java Interview program on increment and decrement operator in expression.


  1. package com.instanceofjava;
  2.  
  3. class IncrementDemo{
  4.  
  5. public static void main(String [] args){ 

  6.     int a=20;
  7.   a= a--  + ++a;
  8.  
  9.     System.out.println(a);
  10.  
  11. }
  12. }
Output:
  1. 40

16.increment and decrement operators Inside println() method:



  1. package com.instanceofjava;
  2.  
  3. class IncrementDemo{
  4.  
  5. public static void main(String [] args){ 

  6.    int a=1;
  7.  
  8.     System.out.println(a++);
  9.     System.out.println(a++);
  10.     System.out.println(++a);
  11.  
  12.     System.out.println(a++);
  13.     System.out.println(a++);
  14.  
  15.     System.out.println(a--);
  16.     System.out.println(a--);
  17.  
  18.     System.out.println(--a);
  19.     System.out.println(--a);
  20.     System.out.println(a--);
  21.  
  22. }
  23. }
Output:
  1. 1
  2. 2
  3. 4
  4. 4
  5. 5
  6. 6
  7. 5
  8. 3
  9. 2
  10. 2

17.Java Interview program on increment and decrement operator in println


  1. package com.instanceofjava;
  2.  
  3. class IncrementDemo{
  4.  
  5. public static void main(String [] args){ 

  6.    int i=15;
  7.     System.out.println(i++);
  8.     System.out.println(i--);
  9.  
  10. }
  11. }
Output:
  1. 15
  2. 16

18.Java Interview program on increment and decrement operator in println


  1. package com.instanceofjava;
  2.  
  3. class IncrementDemo{
  4.  
  5. public static void main(String [] args){ 

  6.     int a=10,b=10;
  7.  
  8.      for(int i=0;i<5;i++){
  9.  
  10.          if(++a>2||++b>2){
  11.             a++;
  12.            }
  13.  
  14.       }
  15.      System.out.println("a= "+a+" b="+b);
  16.  
  17. }
  18. }
Output:
  1. 20
  2. 10

   

19.Java Interview program on increment and decrement operator in loops


  1. package com.instanceofjava;
  2.  
  3. class IncrementDemo{
  4.  
  5. public static void main(String [] args){ 

  6.     int i;
  7.  
  8.     for( i=1;i<4;i++){    
  9.            
  10.          System.out.println(i);
  11.  
  12.       }
  13.       System.out.println("value of i after completion of loop: "+i);
  14.  
  15. }
  16. }
Output:
  1. 1
  2. 2
  3. 3
  4. value of i after completion of loop: 4

20.Java Interview program on increment and decrement




  1. package com.instanceofjava;
  2.  
  3. public class A{

  4.  
  5.  static int a = 1111;
  6.  static
  7.  {
  8.         a = a-- - --a;
  9.  }
  10.     
  11. {
  12.         a = a++ + ++a;
  13.  }
  14.  
  15.  public static void main(String[] args)  {
  16.  
  17.        System.out.println(a);
  18.  
  19.     }
  20.  
  21. }

Output:
  1. 2
Select Menu