Learn Java Multithreaded State Transitions

Java multithreading has five states: new, ready, running, blocked, and finished.

  • New state: It is to create a thread object, that is, to create a new thread without doing any other actions, which is equivalent to initializing the thread;
  • Ready state: If the current state of the thread is new , then executing the thread's start() method will update the thread state to ready. Note that when the state of the thread is ready, the thread has not actually run, but is just queued for the CPU time slice. If the current state of the thread is blocked, the thread will update the state to ready in the following situations: 1) the current thread acquires the synchronization lock; 2) the sleep time of the current thread ends; 3) the blocking IO of the current thread is completed; 4) The execution of the current thread join method ends;
  • Running state: The current thread has obtained the running time slice of the CPU, and actually executes the program code in the CPU;
  • Blocking state: In the following cases, the thread state will be converted to blocking state: 1) The thread calls the wait method; 2) The thread calls the sleep method; 3) The thread calls the join method; 4) The thread does not acquire a synchronization lock; 5) Only blocking IO is used in the thread;
  • End state: usually the thread running ends or an exception occurs during the thread running;

Let's talk about the transition of thread state in vernacular:

When a new thread is created, the state of the thread is new; when the thread calls the start method, the thread first enters the ready state (at this time, it is unknown whether the CPU is processing other threads at full capacity), If the CPU is in an idle state at this time, the thread will immediately change from the ready state to the running state; if the thread in the running state is not disturbed by other threads, it will successfully execute the program code of the thread; but if it is affected by other threads (for example, when a large number of threads are initiated, the CPU will reallocate time slices), or if the thread needs to pause for a while at a certain time, the thread enters the blocking state; when the thread enters the blocking state, if it is because of calling If the wait method is used, then you need to wait for other threads to wake up; if the sleep/join method is called, you need to wait for the end of the method to enter the ready state......until the thread completes the task.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325646440&siteId=291194637