Skip to content
  • Facebook
GeekCer Logo

GeekCer

The geek's Coding education and Review centre

  • Home
  • Tutorials
    • Java
    • Servlet
    • JSP
    • Python
    • C Tutorial
    • Spring
    • Spring Boot
    • MongoDB
    • Hibernate
    • Data Structure
  • General Knowledge
  • Biography
  • Grammar
  • Festival (त्योहार)
  • Interview
  • Differences
  • Important
  • Toggle search form

Home » Java » Multithreading in java, Thread, Runnable | Life Cycle of Thread

  • State the Universal law of gravitation | Law of Gravity, Formula
    State the Universal law of gravitation | Law of Gravity, Formula Science
  • Diwali The Festival of Lights
    Diwali 2022, Indian Festival of Lights essay (दिवाली त्योहार पर निबंध, कहानी) Festival
  • Ganesh Chaturthi Puja in Hindi | गणेश चतुर्थी का व्रत, महत्व, कथा
    Ganesh Chaturthi Puja in Hindi | गणेश चतुर्थी का व्रत, महत्व, कथा Festival
  • Maharishi Valmiki in Hindi, Biography, Dacoit Ratnakar, Jayanti
    Maharishi Valmiki in Hindi, Biography, Dacoit Ratnakar, Jayanti Spiritual
  • Famous Slogans given by famous Personalities Indian leaders
    Famous Slogans of freedom fighters in Hindi | स्वतंत्रता सेनानियों के प्रसिद्ध नारे हिंदी में General Knowledge
  • States of Matter : Physical Properties of Matter (Solid, Liquid, Gas)
    States of Matter | Physical Properties of Matter (Solid, Liquid, Gas) Science
  • Thomas Edison Biography in Hindi - थॉमस एडिसन जीवनी
    Thomas Edison Biography in Hindi – थॉमस एडिसन जीवनी Biography
  • Amitabh Bachchan biography in hindi | Family, wife, awards
    Amitabh Bachchan biography in hindi | Family, wife, awards Biography

Multithreading in java, Thread, Runnable | Life Cycle of Thread

Posted on September 1, 2021June 4, 2022 By GeekCer Education No Comments on Multithreading in java, Thread, Runnable | Life Cycle of Thread
Multithreading in java

A multithreading in Java is a concept where we split a program into two or more sub-programs and execute them at the same time.

If we take real world example, we can assume that there is a task which we divide into sub tasks and assign them to different people for execution independently and simultaneously. The main objective of multitasking is to improve the performance of the system by reducing the response time.

Before going into the details of multithreading, let’s get an idea about threads.

Table of Contents

  • What is Thread in Java?
    • Ways to define thread in Java
  • Defining a thread by extending Thread class
      • Steps of creating Thread and running it
  • start() Vs run() method Multithreading in java
  • Defining a thread by implementing Runnable interface
    • Steps of creating thread by using Runnable interface
  • Life Cycle of Thread in Java
  • sleep Vs wait method in java
  • Thread Schedular
  • Thread Priority
  • Prevent Thread execution
    • yield() method
    • join() method
    • sleep() method
  • Thread Interruption in Java

What is Thread in Java?

When more than one task is executed simultaneously, where each task is a separate independent part of the same program, that independent part of the program is called a Thread.

It is light-weight because it uses minimum resources of the system, it means thread takes less memory and less processor time.

Ways to define thread in Java

There are mainly two ways to define thread which are as follows:

  • By extending Thread class.
  • By implementing Runnable interface.

Defining a thread by extending Thread class

In this way we extends a Thread class and override the run() method. In this method of thread creation, you need not to create Thread class object implicitly because when you create an object of child class the Thread class constructor will also invoked.

Steps of creating Thread and running it

  • Create a class that extends Thread class.
  • Override the run() method.
  • Create an object to the created class.
  • Use start() method to run the thread.
                  public class ThreadDemo extends Thread {

        @Override    
	public void run() {
		for (int i = 1; i <= 5; i++) {
			System.out.println("Child Thread");
		}
	}

	public static void main(String[] args) {
		ThreadDemo obj = new ThreadDemo();
		obj.start();
		for (int i = 1; i <= 5; i++) {
			System.out.println("Main Thread");
		}
	}
}

Output:
Child Thread
Child Thread
Main Thread
Child Thread
Main Thread
Main Thread
Child Thread
Main Thread
Main Thread
Child Thread

start() Vs run() method Multithreading in java

If you call the start() method then new thread will be created and that thread executes the run() method.

If you call the run() method directly then no new thread will be created and run() method will execute just like a normal method.

Defining a thread by implementing Runnable interface

You can define thread by implementing Runnable interface which is present in java.lang package and it only contains run() method.

Steps of creating thread by using Runnable interface

  • Declare a class and implement Runnable interface.
  • Override the run() method.
  • Create an object of created class.
  • Create an object of Thread class and pass the object of created class into the constructor of Thread class.
  • Call start() method.
                  public class ThreadDemo implements Runnable {

	@Override
	public void run() {
		for (int i = 1; i <= 5; i++) {
			System.out.println("Child Thread");
		}
	}

	public static void main(String[] args) {
		ThreadDemo obj = new ThreadDemo();
		Thread t = new Thread(obj);
		t.start();
		for (int i = 1; i <= 5; i++) {
			System.out.println("Main Thread");
		}
	}
}

Output:
Main Thread
Child Thread
Child Thread
Main Thread
Child Thread
Main Thread
Main Thread
Child Thread
Child Thread
Main Thread

Life Cycle of Thread in Java

There are 5 states in Java Thread. A thread is always in one of these five states. It can move from one state to another.

  • New: When new Thread object is created.
  • Ready/Runnable: When start() method of Thread class is invoked.
  • Running: If thread scheduler allocates the CPU.
  • Waiting/Non-Runnable/Blocked: When the thread is still alive, but is currently not eligible to run.
  • Terminated: If run() method completes then it enters into the terminated state.

When you create a Thread class object, a thread will born. Then, when you call the start() method, the thread goes into runnable state. It is possible that yield() method may pause a thread, but the tread will be still in runnable state. When sleep() or wait() methods act on thread, a thread may get into non-runnable state. if user provides required input/output, the thread comes out from the non-runnable state, and it comes back into the runnable state. When a thread comes out of run() method, a thread is terminated from memory.

All these state transitions of a thread are called “thread life cycle”.

sleep Vs wait method in java

There are following differences between sleep and wait method in java.

#sleep() methodwait() method
1Thread class includes the sleep method.The wait function belongs to the Object class.
2The sleep method is a static method. The wait method is a instance method.
3When the timer ends, the sleep() function will be immediately woken up.Another thread can wake up a wait() by invoking notify() or notifyAll().
4Before entering the waiting state, this method does not release the lock. This method will release the lock before going to waiting state.
5This method does not require a synchronized block to be called.Only synchronized context (method or block) will call this method.

Thread Schedular

The thread scheduler decides which thread should run. In other words, the thread scheduler decides which thread will get the first chance if multiple threads wait for a chance to execute. It is the part of JVM and the behavior of the thread scheduler is vendor specific.

In case of multithreading in java we can tell the possible output but not the exact output.

Thread Priority

Thread priority affects the order in which the thread scheduler allocates CPU. The highest priority thread will get the chance first and the lowest priority thread will get the chance last.

If multiple threads have same priority then you cannot expect execution order, it will depend on thread scheduler.

Default priority of a thread is 5. The value of minimum priority of a thread is 1 and maximum priority of a thread is 10.

Thread class defines the following constants for the thread priority

  • Thread.MIN_PRIORITY – 1
  • Thread.MAX_PRIORITY – 10
  • Thread.NORM_PRIORITY – 5

Thread scheduler uses these priority to allocate the CPU.

Thread class defines the following two methods to get and set the priority of a thread.

public final int getPriority();
public final void setPriority(int priority);

As you know you can put the number from 1 to 10, if you put other than these values then you will get IllegalArgumentException.

Prevent Thread execution

There are following methods by which you can prevent thread execution

  1. yield()
  2. join()
  3. sleep()

Let’s discuss about these three method which prevent java thread execution in multithreading as well.

yield() method

The yield() method pauses the current executing thread to give a chance to other remaining waiting threads of the same priority.

If there is no waiting thread or all the waiting threads have a lower priority then the same thread will once again continue its execution.

public static native void yield();

join() method

If a thread wants to wait till the completion of another thread then we should use join() method.

If there are two threads, t1 and t2, if t1 executes t2.join(), then t1 will enter into the waiting state until t2 completes. Once t2 completes then t1 will continue its execution.

public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
public void join(long milliseconds, int nanoseconds)throws InterruptedException

sleep() method

If a thread do not want to perform any operation for some time then we should use sleep() method. It pauses the thread execution for a particular amount of time.

public static void sleep(long milliseconds)throws InterruptedException
public static void sleep(long milliseconds, int nanoseconds)throws InterruptedException

Thread Interruption in Java

In the multithreading environment, a thread can interrupt another waiting or sleeping thread

public void interrupt();

If you call the interrupt() method, you may not see the effect immediately. Whenever you call the interrupt() method, if the target thread is not in the waiting or sleeping state, the interrupt call will wait until the target thread enters the sleeping or waiting state. The interrupt call will take effect on the target thread once the target thread enters the sleeping or waiting state.

In conclusion, by going through this article hope you got an idea of threading , multithreading in java and how to create a thread by using Thread class and Runnable interface.

Share this:

  • Click to share on Facebook (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • More
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)

Also Read

Java Tags:Life Cycle, Multithreading, Synchronization, Thread, Thread Safe

Post navigation

Previous Post: Vector in Java Collection, Constructors, Example Programs
Next Post: Thread Synchronization in Java | Synchronized Method & Block

More Related Articles

Method Overloading in Java Method Overloading in Java Java
Java Keywords Java Keywords Java
Jenkins java | Installing Jenkins on Windows Jenkins java | Installing Jenkins on Windows Important
Steps of Database Connectivity in Java Steps of Database Connectivity in Java Java
Java 8 Stream map example | Java 8 map(function) parameter Java 8 Stream map example | Java 8 map(function) parameter Java
Variables in Java Variables in Java Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Java Home
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Keywords
  • Java Operators
  • Java If-else Statement
  • Java Switch
  • Java Loop
  • Java Arrays
  • Method Overloading in Java
  • Java OOP
  • Java Collections
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Multithreading in java
  • Thread Synchronization
  • Exception Handling
  • Java JDBC Driver
  • Java Database Connectivity steps
  • Lambda Expressions
  • Concurrent Collections
  • National Farmers Day in Hindi | राष्ट्रीय किसान दिवस पर निबंध | चौधरी चरण सिंह जयंती
  • Human rights day in Hindi: 10 दिसंबर ह्यूमन राइट्स डे
  • Unicef day is celebrated on December 11 | Speech on unicef day
  • Indian Navy Day: जल सेना दिवस कब और क्यों मनाया जाता है?
  • P V Sindhu Biography in Hindi, Badminton, State, Caste पी. वी. सिंधु जीवन परिचय, कहानी, राज्य, जाति
  • Draupadi Murmu Biography In Hindi | द्रौपदी मुर्मू की जीवनी
  • OSI Model | 7 Layers of OSI Model in Computer network
    OSI Model | 7 Layers of OSI Model in Computer network, Functions Networking
  • Difference between TCP and UDP
    Difference between TCP and UDP | TCP vs UDP examples Differences
  • Network kya hai (नेटवर्क क्या है)
    Network kya hai (नेटवर्क क्या है) Networking
  • TCP/IP Model, Full Form, Layers and their Functions
    TCP/IP Model, Full Form, Layers and their Functions Networking
  • Difference between Internet and Intranet
    Difference between Internet and Intranet Differences
  • Similarities and difference between OSI and TCP/IP model
    OSI vs TCP/IP Model, Similarities and difference between OSI and TCP/IP model Networking
  • IPv4 Vs IPv6 | Difference between IPv4 and IPv6
    IPv4 Vs IPv6 | Difference between IPv4 and IPv6 Differences
  • Java Tutorial
  • Servlet Tutorial
  • JSP Tutorial
  • Maven Tutorial
  • HTML Tutorial
  • Programs
  • Hindi/English Grammar
  • Difference Between ... and ...
  • HR Interview
  • Important Articles

Write to Us:
geekcer.code@gmail.com

  • About Us
  • Privacy and Policy
  • Disclaimer
  • Contact Us
  • Sitemap

Copyright © GeekCer 2022 All Rights reserved