The six states and transitions of java threads

1. Two-way arrow: the state can be converted to each other; one-way arrow: the state can only be converted in one direction;

2.NEW: Create the java thread initial object, the thread has not been running yet, calling the start method will become the RUNNABLE state;

3. RUNNABLE: In operation, can be run, blocked (operating system);

4. WAITING: waiting state; t thread calls synchronized (obj) under the premise that the object lock is acquired

(1) Line 2: Call wait, notify, notifyAll, interrupt can be converted to RUNNABLE; the above are all based on the synchronized heavyweight lock (pessimistic lock); after waking up, the competition succeeds: WAITING --> RUNNABLE, the competition fails : WAITING --> BLOCKED;

(2) Line 3: call t.join to make the calling thread enter the monitor monitor of the t thread object and wait, the current thread is from RUNNABLE --> WAITING; t thread ends, or the current thread calls interrupt, the current thread starts from WAITING - > RUNNALBE;

(3) Line 4: The current thread calls LockSupport.park(), the current thread is from RUNNABLE --> WAITING; the current thread calls LockSupport.unpark() or interrupt, and the current thread is from WAITING --> RUNNABLE;

5. TIMED_WAITING: time-limited waiting; t thread calls synchronized (obj) under the premise that the object lock is acquired

(1) Line 5: The current thread calls obj.wait(long n), and the t thread starts from RUNNABLE --> TIMED_WAITING; when the t thread waits for more than n milliseconds, or when notify, notifyAll, or interrupt is called, the competition succeeds: TIMED_WAITING --> RUNNABLE; Competition failure: TIMED_WAITING --> BLOCKED;

(2) Line 6: The current thread calls join(long n), and the current thread starts from RUNNABLE --> TIMED_WAITING; the current thread waits for more than n milliseconds, or the operation ends, or when interrupt is called, TIMED_WAITING --> RUNNABLE;

(3) Line 7: When the current thread calls sleep(long n), the current thread goes from RUNNABLE --> TIMED_WAITING; when the waiting time exceeds n milliseconds, TIMED_WAITING --> RUNNABLE;

(4) Line 8: When the current thread calls LockSupport.parknanos (long nanos) or LockSupport.parkUntil (long millis), the current thread goes from RUNNABLE --> TIMED_WAITING; when LockSupport.unpark (target thread) is called, interrupt or wait timeout , TIMED_WAITING --> RUNNABLE;

6. BLOCKED: Blocked state, t thread execution of synchronized (obj) fails to obtain the object lock, RUNNABLE --> BLOCKED; the synchronization code block of the thread holding the obj lock is executed, and all BLOCKED threads on the obj object are awakened to compete again, if t thread is successful, BLOCKED --> RUNNABLE; other failed threads are still BLOCKED;

7.TEMINATED: All codes of the current thread have been executed;

 

 

Guess you like

Origin blog.csdn.net/weixin_44182586/article/details/108984739