Table of Contents
What is Thread?
States of  Thread Life Cycle in Java
How to Create a Thread in Java?
Methods of Thread Life Cycle in Java
Home Java javaTutorial Thread Life cycle in Java

Thread Life cycle in Java

Aug 30, 2024 pm 04:19 PM
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 of this Website
    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

    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

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

    Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

    PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

    PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

    PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

    PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

    PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

    PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

    Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

    Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

    PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

    PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

    Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

    Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

    PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

    The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

    See all articles