The life cycle of a thread

  • New
  • Ready (Runnable)
  • Running
  • They are Blocked.
  • In the Dead

New and ready states

new
  • When a program creates a thread using the new keyword, the thread is created, just like any other Java object, and is allocated memory by the Java virtual machine and initialized with the values of its member variables. The thread object does not exhibit any dynamic characteristics of a thread, and the program does not execute the thread body of a thread.
ready
  • After a thread object calls the start() method, the thread is in the ready state, and the Java virtual machine creates a method call stack and program counter for it. The thread in this state is not running, but is ready to run. When the thread starts running depends on the thread scheduler in the JVM.

Pay special attention to

  • Start threads use the start() method instead of the run() method. Never call the run() method of a thread object.
  • Call the start() method to start the thread, and the system treats the run() method as if it were the thread body.
  • But if you call the run() method of a thread object directly, the run() method is executed immediately, and no other thread can execute concurrently until the run() method returns. That is, the system treats the thread object as a normal object, and the run() method is a normal method, not the thread body.

Running and blocking and ready states

run
  • If a thread in the ready state acquires the CPU and begins executing the thread body of the run() method, it is running.
blocking
  • The thread calls the sleep() method to voluntarily abandon the occupied processor resources, and the thread enters the blocking state.
  • The thread calls a blocking IO method and blocks before the method returns.
  • A thread is trying to acquire a synchronization listener that is being held by another thread, that is, waiting for a synchronization lock, the thread is blocked.
  • The thread is waiting for a notify.
  • The program calls the suspend() method of the thread to suspend it. However, this method is prone to deadlocks, so it should be avoided as much as possible.
ready
  • It’s time to sleep ()
  • IO method returns
  • Acquire synchronization lock
  • Receive notification
  • resume()

The thread of death

  • The thread’s run() or call() method completes, and the thread terminates normally.
  • The thread throws an uncaught Exception or Error.
  • A thread calls the stop() method directly to terminate the thread. This method is prone to deadlocks and is generally not recommended.