IT干货网

线程的状态

itxm 2022年03月12日 编程设计 146 0

线程的状态

线程状态包括NEW、就绪状态、运行状态、TIMED_WAITING、阻塞状态和终止状态。终止后,线程无法再次启动。

以下代码演示如何打印线程的状态:

package com.cxf.multithread.state; 
 
public class TestForState { 
    public static void main(String[] args) { 
        Thread thread = new Thread(()->{ 
            try { 
                Thread.sleep(1); 
            } catch (InterruptedException e) { 
                e.printStackTrace(); 
            } 
            for (int i = 0; i < 5; i++) { 
                System.out.println("i am running"); 
            } 
        }); 
        Thread.State state = thread.getState(); 
        System.out.println("after create:"+state); 
        thread.start(); 
        state = thread.getState(); 
        System.out.println("after start:"+state); 
        while(state!=Thread.State.TERMINATED){ 
            state=thread.getState(); 
            System.out.println("when running:"+state); 
        } 
        System.out.println("end:"+state); 
    } 
} 
 

输出结果:

after create:NEW 
after start:RUNNABLE 
when running:RUNNABLE 
when running:RUNNABLE 
when running:RUNNABLE 
when running:RUNNABLE 
when running:RUNNABLE 
when running:RUNNABLE 
when running:RUNNABLE 
when running:RUNNABLE 
when running:RUNNABLE 
when running:RUNNABLE 
when running:RUNNABLE 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:TIMED_WAITING 
when running:RUNNABLE 
i am running 
i am running 
i am running 
i am running 
i am running 
when running:BLOCKED 
when running:TERMINATED 
end:TERMINATED 

此处线程创建后进入NEW状态,start后进入RUNNABLE状态,用sleep方法后进入TIMED_WAITING状态,TIMED_WAITING结束后重新进入RUNNABLE状态,RUNNABLE状态持续一段时间后开始真正的运行线程,线程有IO行为时被主线程抢走运行机会,进入阻塞状态。线程运行结束进入终止状态。


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

java线程中的join方法