search
HomeJavajavaTutorialThread Life cycle in Java

A thread experiences numerous phases in the life cycle. Such as, a thread comes into the world, started out, runs, and after that passes away. The subsequent diagram explains the complete life cycle of the thread.

Thread Life cycle in Java

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  • Thread Constructor produces a thread through a new state.
  • Calling begin the method in Thread can make it through the runnable state.
  • Thread Scheduler concerning Java runs that thread when the processor receives it.
  • When the thread goes to a blocked state, it will run yet again because it comes back to a runnable state.
  • If the wait method is referred to as thread would go to waiting for the state, it will go to a runnable state soon after it becomes notification throughout the Inform and a notify all method.
  • The thread ends once the run method terminates.

What is Thread?

A thread is defined at the Operating System level. And the Java language, as well as all the other languages, uses leverages the service that the Operating System gives. From the developer’s point of view, a thread is a set of instructions that we are going to write our application and execute in a certain way. An application itself can be composed of several threads. Different threads can be executed at the same time. The JVM (Java Virtual Machine) works with several threads. There are threads for the garbage collection. There are threads for the Just in Time Compiler and other technical threads.

States of  Thread Life Cycle in Java

Below are the different States of the Thread Life Cycle in Java:

1. New: A new thread starts its life cycle inside the new state. It continues to be with this state before the program begins the thread. Additionally, it is known as a created thread.

2. Runnable: After a recently born thread can begin, the thread turns into runnable. A thread with this state is considered performing their process.

3. Waiting: Occasionally, a thread transition towards the waiting around the state even though the thread is waiting for another thread to execute an activity. A thread transition to the runnable state only if an additional thread indicates the waiting thread to keep performing.

4. Timed Waiting: A runnable thread cans easily the particular timed waiting for the state to get a specific interval of the time. A thread with this state transitions returning to the runnable state once that point interval expires or if the event it truly is awaiting happens.

5. Terminated: A runnable thread gets into the terminated state because it accomplishes its task or else terminates.

How to Create a Thread in Java?

The most basic way to create a thread in Java is to use the Runnable Pattern. First, you need to create an instance of the Runnable interface, which is very easy; there is only one method to implement. Then we pass this instance to the constructor of the Thread class. And then, we just call the start() method of this thread object created to launch a new thread that is going to run the task wrapped in our Runnable object.

Thread Life cycle in Java

So first, we create an instance of a Runnable.  There is only one method to implement, which is called the run() method. This is the Java 7 pattern to do that, with an instance of an anonymous class. But we can also use a lambda expression to implement a Runnable since there is only one method in the Runnable interface.

Thread Life cycle in Java

Let us create threads on very simple examples.

We are going to see what can go wrong with a race condition that is with unsynchronized code that should be synchronized, and we are going to fix our code using synchronization. This first example is very simple; it’s very basic. It is just about creating a task.

Thread Life cycle in Java

Output:

Thread Life cycle in Java

A task is an instance of the Runnable interface, let us call it runnable, and we can implement this interface using a lambda expression. This task is given to a new thread and executed in the context of this thread. So we are just going to print out the name of the thread that is running this task. I am running in… Thread.currentThread() is a static method of the Thread class that returns the thread running the current task. And we just have to call getName() on this thread object to return the name of a thread, then after we create a Thread instance t = new Thread.  Passing this runnable as a parameter. So this thread is going to execute this piece of code. And to launch it. t.start() this is the start() method that we need to call. We can also give an explicit name of this Thread using t.setName(“My thread”). And now we can execute this code. Now instead of the call start() method, we call the run() method, and if we run this code, the problem is that the task is correctly executed, but it is not executed in the thread we have created. It is executed in the main thread, which is the thread executing the main method. So this run() method should not be called if we want to launch a new thread.

Thread Life cycle in Java

Output:

Thread Life cycle in Java

Methods of Thread Life Cycle in Java

The methods described by simply Thread are presented in Table.

Data Types Thread Method Names
String

getName()

Return this thread’s name

int get priority()

Returns the thread’s priority

boolean isAlive()

Tests if this thread is still running

void join()

Waits for this thread to die (terminate)

void run()

Whenever this thread was built utilizing an individual Runnable object, which usually Runnable object’s run method is called, this method will do nothing and returns. Whenever thread class can be extended and run() method is over-ridden during sub-class, then an over-ridden run() method is called.

void setName(String name)

Alterations the name with this thread to become comparable to the argument name.

static void

 

 

sleep(long millis) throws Interrupted/Exception
It causes the presently performing thread to rest for
the required quantity of milliseconds.
static void sleep(long millis, int Nanos) throws InterruptedException

It causes the presently performing thread to sleep (cease execution) for the required quantity of milliseconds as well as the particular quantity of nanoseconds.

void start()

Triggers these threads to start execution; the Java Virtual Machine calls the run method of that thread.

static void yield()

Triggers the presently thread object to pause and permit additional threads to execute briefly.

static Thread currentThread()

Returns a mention of the presently executing thread object.

Data Types

Thread Method Names
    String

  • getName()
  • Return this thread’s name

  • int
  • get priority()
  • Returns the thread’s priority
    boolean isAlive() Tests if this thread is still running
    void join() Waits for this thread to die (terminate)
    void run() Whenever this thread was built utilizing an individual Runnable object, which usually Runnable object’s run method is called, this method will do nothing and returns. Whenever thread class can be extended and run() method is over-ridden during sub-class, then an over-ridden run() method is called.
    void setName(String name) Alterations the name with this thread to become comparable to the argument name.
    static void     sleep(long millis) throws Interrupted/Exception
    It causes the presently performing thread to rest for
    the required quantity of milliseconds.
    static void sleep(long millis, int Nanos) throws InterruptedException It causes the presently performing thread to sleep (cease execution) for the required quantity of milliseconds as well as the particular quantity of nanoseconds.
    void start() Triggers these threads to start execution; the Java Virtual Machine calls the run method of that thread.
    static void yield() Triggers the presently thread object to pause and permit additional threads to execute briefly.
    static Thread currentThread() Returns a mention of the presently executing thread object.
    Conclusion Simple to begin using threads, extremely difficult to grasp. Designing classes that contain methods that can be thread secure is challenging. Read: JavaDoc to get the class java.lang.Thread

    The above is the detailed content of Thread Life cycle in Java. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

    Start Spring using IntelliJIDEAUltimate version...

    How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

    When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

    How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

    How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

    How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

    Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

    How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

    Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

    E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

    Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

    How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

    How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software