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

Table of Contents
1. Thread state diagram
2. State detailed description
1. Initial state (NEW)
2.1. Ready state (READY of RUNNABLE)
2.2. Running state (RUNNING of RUNNABLE)
3. Blocked state (BLOCKED)
6. Termination status (TERMINATED)
3. Waiting queue
4. Synchronization queue status
5. Comparison of Several Methods
Home Java JavaBase There are several thread states in java

There are several thread states in java

Nov 24, 2022 pm 04:03 PM
java

Java has 6 thread states: initial (NEW), running (RUNNABLE), blocked (BLOCKED), waiting (WAITING), timeout waiting (TIMED_WAITING), and terminated (TERMINATED). Use the new keyword to create a new thread, but the start() method has not been called. The thread is in the new state; the blocked state indicates that the thread is waiting for the monitor lock and is trapped in the state; the thread that enters the waiting state needs to wait for other threads to make a decision Some specific action (notification or interrupt).

There are several thread states in java

#The operating environment of this tutorial: windows7 system, java8 version, Dell G3 computer.

The status of threads in Java is divided into 6:

1. Initial (NEW): A new thread object is created, but the start() method has not been called yet.
2. Run (RUNNABLE): In Java threads, the two states of ready and running are generally called "running".
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 and obtain the right to use the CPU. At this time, it is in the ready state. The thread in the ready state becomes running after obtaining the CPU time slice.
3. Blocked (BLOCKED): Indicates that the thread is blocked in the lock.
4. Waiting(WAITING): The thread entering this state needs to wait for other threads to make some specific actions (notification or interruption).
5. Timeout waiting (TIMED_WAITING): This state is different from WAITING, it can return by itself after the specified time.
6. TERMINATED(TERMINATED): Indicates that the thread has completed execution.

These 6 states are defined in the State enumeration of the Thread class. You can view the source code for one-to-one correspondence.

1. Thread state diagram

There are several thread states in java

2. State detailed description

1. Initial state (NEW)

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

2.1. Ready state (READY of RUNNABLE)

  • The ready state only means that you are qualified to run. If the scheduler does not select you, you will Always Ready state.

  • Call the start() method of the thread, and the thread enters the ready state.

  • The sleep() method of the current thread ends, other threads join() ends, waiting for the user input to complete, a thread gets the object lock, these threads will also enter Readystate.

  • The current thread's time slice is used up, the yield() method of the current thread is called, and the current thread enters the ready state.

  • After the thread in the lock pool obtains the object lock, it enters the ready state.

2.2. Running state (RUNNING of RUNNABLE)

When the thread scheduler selects a thread from the runnable pool as the current thread, The state in which it is located. This is also the only way for a thread to enter the running state.

3. Blocked state (BLOCKED)

The blocking state is the state when the thread blocks entering the method or code block (acquiring the lock) modified by the synchronized keyword.

4. Waiting(WAITING)

Threads in this state will not be allocated CPU execution time. They must wait to be explicitly awakened, otherwise they will be in Indefinitely waiting state.

5. Timeout waiting(TIMED_WAITING)

The thread in this state will not be allocated CPU execution time, but there is no need to wait indefinitely to be explicitly awakened by other threads , they will wake up automatically after a certain time.

6. Termination status (TERMINATED)

  • #When the run() method of the thread is completed, or the main() method of the main thread is completed , we consider it to be terminated. This thread object may be alive, but it is no longer a separately executed thread. Once a thread is terminated, it cannot be revived.

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

3. Waiting queue

  • Before calling the wait() and notify() methods of obj, you must obtain the obj lock, that is, it must be written in synchronized( obj) within the code segment.
  • Steps and diagrams related to waiting queues

There are several thread states in java

  • ##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 synchronization queue. If thread 5 calls the notify() method of object A, a thread will be awakened. It is not known who will be awakened, and the awakened thread will enter the synchronization queue.

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

  • The threads in the synchronization queue compete for the object lock, but it is not known when thread 1 can grab it.

4. Synchronization queue status

  • When the current thread wants to call the synchronization method of object A, it finds that the lock of object A is locked. occupied by the thread, at this time the current thread enters the synchronization queue. In short, Synchronization Queue 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 synchronization queue to compete for the object lock.
  • Synchronization queue is a concept that only exists in a synchronization environment. One object corresponds to a synchronization queue.
  • After the thread waiting time is up or is awakened by notify/notifyAll, it will enter the synchronization queue to compete for the lock. If it obtains the lock, it will enter the RUNNABLE state, otherwise it will enter the BLOCKED state and wait to obtain the lock.

5. Comparison of Several Methods

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

  • Thread.yield(), the current thread must call this method. The current thread gives up the acquired CPU time slice, but does not release the lock resource, and changes from the running state to the ready state. The OS selects 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. This method is similar to sleep(), except that the user cannot specify how long to pause.

  • thread.join()/thread.join(long millis), the current thread calls the join method of other thread t, and the current thread enters the WAITING/TIMED_WAITING state , the current thread will not release the object lock already held. When thread t completes execution or the millis time expires, the current thread generally enters the RUNNABLE state, and may also enter the BLOCKED state (because join is implemented based on wait).

  • 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) to wake up automatically when the timeout time expires.

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

  • LockSupport.park()/LockSupport.parkNanos(long nanos),LockSupport.parkUntil(long deadlines), the current thread enters the WAITING/TIMED_WAITING state. Compared with the wait method, the thread can enter the WAITING/TIMED_WAITING state without obtaining the lock, and needs to be awakened through LockSupport.unpark (Thread thread).

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of There are several thread states 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

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)

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.

python itertools combinations example python itertools combinations example Jul 31, 2025 am 09:53 AM

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

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

python pytest fixture example python pytest fixture example Jul 31, 2025 am 09:35 AM

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

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

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

Troubleshooting Common Java `OutOfMemoryError` Scenarios Troubleshooting Common Java `OutOfMemoryError` Scenarios Jul 31, 2025 am 09:07 AM

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

See all articles