Several ways of thread

thread state

insert image description here

  • NEW: The job is arranged, and the action is not yet started (the Thread object is created, but the start method has not been called, and the system kernel has no threads yet)
  • RUNNABLE: Workable, can be divided into working and about to start working (ready state, there are two types: 1. Running on the CPU, 2. Not yet running on the CPU, but ready)
  • BLOCKED: These all mean waiting in line for other things (waiting for locks, entering a blocked state)
  • WAITING: These all mean waiting in line for other things (wait is called in the thread to enter the blocking state)
  • TIMED_WAITING: These all indicate waiting in line for other things (blocking state entered through sleep in the thread)
  • TERMINGTED: The work is completed (the thread in the system has been executed and destroyed (equivalent to the execution of run, but the Thread object is still there))
    insert image description here
public class Demo12 {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        Thread t = new Thread(() -> {
    
    
            System.out.println("hello thread");
            try {
    
    
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        });

        // 在 start 之前获取. 获取到的是线程还未创建的状态
        System.out.println(t.getState());

        t.start();
        // Thread.sleep(500);
        System.out.println(t.getState());
        t.join();

        // 在 join 之后获取. 获取到的是线程已经结束后的状态
        System.out.println(t.getState());
    }

}
运行结果:
    NEW
	RUNNABLE
	hello thread
	TERMINATED

Guess you like

Origin blog.csdn.net/HBINen/article/details/126593154