Thread 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.
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.
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.
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.
Output:
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.
Output:
Methods of Thread Life Cycle in Java
The methods described by simply Thread are presented in Table.
|
Thread Method Names |
||||||||||||||||||||||||
String |
Return this thread’s name |
||||||||||||||||||||||||
int |
|
||||||||||||||||||||||||
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. |
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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 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 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 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.

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 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.

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.

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.
