亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Java JavaBase What are the states of java threads?

What are the states of java threads?

Jul 24, 2020 am 11:37 AM
java Thread status

Five states of java thread: 1. Initial state. 2. Runnable state, located in the runnable thread pool, waiting to be selected by thread scheduling to obtain the right to use the CPU. 3. Running status. 4. Blocked state means that the thread has given up the right to use the CPU for some reason. 5. In the death state, the dead thread cannot be resurrected.

What are the states of java threads?

The life cycle of a thread in Java can be roughly divided into 5 states.

1. Initial state (NEW): A new thread object is created.

2. Runnable (RUNNABLE): After the thread object is created, other threads (such as the main thread) call the start() method of the object. The thread in this state is located in the runnable thread pool, waiting to be selected by thread scheduling to obtain the right to use the CPU.

3. RUNNING: The thread in the runnable state obtains the cpu time slice (timeslice) and executes the program code.

4. BLOCKED: The blocked state means that the thread gives up the right to use the cpu for some reason, that is, it gives up the cpu timeslice and temporarily stops running. Until the thread enters the runnable state, it has the opportunity to obtain the cpu timeslice again and move to the running state. There are three types of blocking situations:

(1). Waiting for blocking: The running thread executes the o.wait() method, and the JVM will put the thread into the waiting queue (waiting queue) middle.

(2) Synchronization blocking: When a running thread acquires the synchronization lock of an object, if the synchronization lock is occupied by another thread, the JVM will put the thread into the lock pool. )middle.

(3) Other blocking: When a running thread executes the Thread.sleep(long ms) or t.join() method, or issues an I/O request, the JVM will set the thread to is in blocking state. When the sleep() state times out, join() waits for the thread to terminate or times out, or the I/O processing is completed, the thread returns to the runnable state.

5. Death (DEAD): When the execution of the thread's run() and main() methods ends, or the run() method exits due to an exception, the thread ends its life cycle. Dead threads cannot be resurrected.

1. Thread state diagram

What are the states of java threads?

##2. Initial state

Implementation Runnable interface and inheritance Thread can get a thread class. When a new instance comes out, the thread enters the initial state

3. Runnable state

1. Runnable state It just means that you are qualified to run. If the scheduler does not select you, you will always be runnable.

2. Call the start() method of the thread, and the thread enters the runnable state.

3. The sleep() method of the current thread ends, and the join() method of other threads ends. After the user input is completed, a thread obtains the object lock, and these threads will also enter the runnable state.

4. When the time slice of the current thread is used up, the yield() method of the current thread is called, and the current thread enters the runnable state.

5. After the thread in the lock pool obtains the object lock, it enters the runnable state.

4. Running state

The state of the thread when the thread scheduler selects a thread from the runnable pool as the current thread. This is also the only way for a thread to enter the running state.

5. Death state

1. When the run() method of the thread is completed, or when the main() method of the main thread is completed, we consider it dead. . This thread object may be alive, but it is no longer a separately executed thread. Once a thread dies, it cannot be revived.

2. Calling the start() method on a dead thread will throw a java.lang.IllegalThreadStateException exception.

6. Blocking state

1. The current thread T calls the Thread.sleep() method, and the current thread enters the blocking state.

2. Other thread t2 running in the current thread calls the join() method, and the current thread enters the blocking state.

3. When waiting for user input, the current thread enters the blocking state.

7. Waiting queue (originally a method in Object, but it affects the thread)

1. Before calling the wait() and notify() methods of obj, The obj lock must be obtained, that is, it must be written in the synchronized(obj) code segment.

2. Steps and diagrams related to the waiting queue

  • Thread 1 acquires the lock of object A and is using object A.

  • Thread 1 calls the wait() method of object A.

  • Thread 1 releases the lock of object A and immediately enters the waiting queue.

  • The objects in the lock pool compete for the lock of object A.

  • Thread 5 obtains the lock of object A, enters the synchronized block, and uses object A.

  • Thread 5 calls the notifyAll() method of object A, wakes up all threads, and all threads enter the lock pool. ||||| Thread 5 calls the notify() method of object A to wake up a thread. It is not known who will be awakened. The awakened thread enters the lock pool.

  • The synchronized notificationAll() method ends and thread 5 releases the lock of object A.

  • The threads in the lock pool compete for the object lock, but it is not known when thread 1 can grab it. ||||| The threads awakened in the original lock pool in Step 6 compete for object locks together.

    What are the states of java threads?

8. Lock pool status

The current thread wants to call the synchronization method of object A When, it is found that the lock of object A is occupied by another thread. At this time, the current thread enters the lock pool state. In short, the lock pool is filled with threads that want to compete for object locks.

When a thread 1 is awakened by another thread 2, thread 1 enters the lock pool state to compete for the object lock.

Lock pool is a concept that only exists in a synchronized environment. One object corresponds to a lock pool.

9. Comparison of Several Methods

Thread.sleep(long millis), this method must be called by the current thread. The current thread enters blocking but does not release the object. After locking and millis, the thread automatically wakes up and enters the runnable state. Function: The best way to give other threads a chance to execute.

Thread.yield(), this method must be called by the current thread. The current thread gives up the acquired cpu time slice, changes from the running state to the runnable state, and allows the OS to select the thread again. Function: Let threads with the same priority execute in turn, but there is no guarantee that they will execute in turn. In practice, there is no guarantee that yield() will achieve the purpose of concession, because the concession thread may be selected again by the thread scheduler. Thread.yield() does not cause blocking.

t.join()/t.join(long millis), the current thread calls the join method of other thread 1. The current thread blocks, but does not release the object lock until thread 1 completes execution or the millis time expires. , the current thread enters the runnable state.

obj.wait(), the current thread calls the wait() method of the object, the current thread releases the object lock and enters the waiting queue. Rely on notify()/notifyAll() to wake up or wait(long timeout) timeout to wake up automatically.

obj.notify() wakes up a single thread waiting on this object monitor. The choice is arbitrary. notifyAll() wakes up all threads waiting on this object monitor.

Recommended tutorial: "java tutorial"

The above is the detailed content of What are the states of java threads?. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Google Chrome cannot open local files Google Chrome cannot open local files Aug 01, 2025 am 05:24 AM

ChromecanopenlocalfileslikeHTMLandPDFsbyusing"Openfile"ordraggingthemintothebrowser;ensuretheaddressstartswithfile:///;2.SecurityrestrictionsblockAJAX,localStorage,andcross-folderaccessonfile://;usealocalserverlikepython-mhttp.server8000tor

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

See all articles