Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What do threads and thread states mean in Java

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the meaning of threads and thread status in Java". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the meaning of threads and thread state in Java"?

Thread thread (English: thread) is the smallest unit that the operating system can schedule operations. It is included in the process and is the actual operating unit of the process. A thread refers to a single order of control flow in a process, where multiple threads can be concurrent in a process, and each thread performs different tasks in parallel. It is also called lightweight process (lightweight processes) in Unix System V and SunOS, but lightweight process refers more to kernel thread (kernel thread) and user thread (user thread) is called thread.

The above is copied from Wikipedia

The tasks and logical operations in the code depend on threads, which is the most valuable resource for java runtime.

Multithreading can increase cpu usage time to a certain extent, squeeze computer resources to provide better performance, and increase resource consumption to some extent, such as memory growth, thread context data switching consumption, cup resource consumption. In fact, we should use thread resources reasonably according to business scenarios.

Java thread life cycle

! [image-20190712155311451] (/ Users/yugj/Library/Application Support/typora-user-images/image-20190712155311451.png)

Https://www.geeksforgeeks.org/lifecycle-and-states-of-a-thread-in-java/contribute.geeksforgeeks.org/wp-content/uploads/threadLifeCycle.jpg

Java.lang.Thread.State defines the following six thread states

/ * Thread state for a thread which has not yet started. * / NEW,/** * Thread state for a runnable thread. A thread in the runnable * state is executing in the Java virtual machine but it may * be waiting for other resources from the operating system * such as processor. * / RUNNABLE,/** * Thread state for a thread blocked waiting for a monitor lock. * A thread in the blocked state is waiting for a monitor lock * to enter a synchronized block/method or * reenter a synchronized block/method after calling * {@ link Object#wait () Object.wait}. * / BLOCKED,/** * Thread state for a waiting thread. * A thread is in the waiting state due to calling one of the * following methods: * * {@ link Object#wait () Object.wait} with no timeout * {@ link # join () Thread.join} with no timeout * {@ link LockSupport#park () LockSupport.park} * *

A thread in the waiting state is waiting for another thread to * perform a particular action. * * For example, a thread that has called Object.wait () * on an object is waiting for another thread to call * Object.notify () or Object.notifyAll () on * that object. A thread that has called Thread.join () * is waiting for a specified thread to terminate. * / WAITING,/** * Thread state for a waiting thread with a specified waiting time. * A thread is in the timed waiting state due to calling one of * the following methods with a specified positive waiting time: * * {@ link # sleep Thread.sleep} * {@ link Object#wait (long) Object.wait} with timeout * {@ link # join (long) Thread.join} with timeout * {@ link LockSupport#parkNanos LockSupport.parkNanos} * {@ link LockSupport#parkUntil LockSupport.parkUntil} * * / TIMED_WAITING,/** * Thread state for a terminated thread. * The thread has completed execution. * / TERMINATED

New: just created, executable, and execution not started

Runnable: is executing or ready to execute, for example, a multithreaded program allocates a specific time slice to a specific thread, and a specific thread executes a short time and pauses to give up cpu time to other threads, so that other threads can execute. In this scenario, threads are ready to execute waiting time for CPU, which is called Runnable.

Blocked:waiting for a monitor lock, which is in a synchronous resource that needs to be locked by other threads, such as waiting for the end of io. This state cannot be executed until it is converted to Runnable and cannot consume cup time slices.

Waiting: waits for other threads to perform specific operations, similar to Blocked

Timed Waiting: thread calls wait for execution scenarios, execute after a specific time, compare sleep, or some conditional wait scenarios, such as scheduled tasks

Terminated: normal or abnormal termination of the thread, no CPU time will be allocated

Simulate thread life cycle

1 Thread state transition

Public class DemonstrateThreadStates2 {static Thread thread1; public static void main (String [] args) {/ / create thread 1 thread1 = new Thread (new TestThread1 ()); / / NEW state after thread1 creation. System.out.println ("State of thread1 after creating it -" >

Console output:

State of thread1 after creating it-NEWState of thread1 after calling. Start () method on it-RUNNABLEState of thread2 after creating it-NEWState of thread2 after calling. Start () method on it-RUNNABLEState of thread2 after calling. Sleep () method on it-TIMED_WAITINGState of thread1 while it called join () method on thread2-WAITINGState of thread2 when it has finished it's execution-TERMINATED

Thread creation thread becomes NEW state, call start to start thread into Runnable, call sleep to block the current thread, become Timed Waiting,thread2 call join, wait for the end of the current thread to parent thread thread1,thread2 thread becomes die, parent thread thread1 waits for thread thread2 to end into waiting

2 simulate blocked scene

Simulate a blocked scene through deadlock

Deadlock condition

Mutually exclusive use: a resource can only be allocated to one thread and is inalienable: the resource can only be released by the occupant, and the applicant cannot forcibly deprive the request for retention: when the thread applies for the resource, keep the possession cycle waiting for the original resource: there is a process waiting queue: {P1, P2, … , Pn}, where P1 waits for the resources occupied by P2, and P2 waits for the resources occupied by P3. Pn waits for the resources occupied by P1 to form a process waiting loop code public class TestDeadLock implements Runnable {/ / flag=1, occupy object o1, wait object O2 / / flag=0, occupy object O2, wait object o1 public int flag=1; / / define two Object objects to simulate the resources occupied by two threads public static Object o1 = new Object (); public static Object O2 = new Object () Public static void main (String [] args) {TestDeadLock deadLock1 = new TestDeadLock (); TestDeadLock deadLock2 = new TestDeadLock (); deadLock1.flag = 0; deadLock2.flag = 1; Thread thread1 = new Thread (deadLock1); Thread thread2 = new Thread (deadLock2); thread1.start (); thread2.start () } @ Override public void run () {System.out.println ("flag:" + flag); / / deadLock2 occupies resource o1 and is ready to acquire resource O2 if (flag = = 1) {synchronized (o1) {try {Thread.sleep (1000) } catch (InterruptedException e) {e.printStackTrace ();} synchronized (O2) {System.out.println ("1") } / / deadLock1 occupies resource O2 and is ready to acquire resource o1 else if (flag = = 0) {synchronized (O2) {try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace () } synchronized (o1) {System.out.println ("0");} references

Https://www.geeksforgeeks.org/lifecycle-and-states-of-a-thread-in-java/

Https://www.jianshu.com/p/8cf78bf94f9d

At this point, I believe you have a deeper understanding of "what is the meaning of threads and thread state in Java". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report