Java 观察线程状态

90 阅读1分钟

用法

Thread thread = new Thread();
Thread.State state = thread.getState();

用例

import java.text.SimpleDateFormat;
import java.util.Date;

public class WatchThread {
    public static void main(String[] args) {
        Thread runnable =new Thread(()->{//lambda表达式
            try
            {
                System.out.println("正在运行的线程名称:runnable "+new SimpleDateFormat("HH:mm:ss:SSS").format(new Date())+"开始");
                Thread.sleep(1);    //延时1毫秒秒
                System.out.println("正在运行的线程名称:runnable "+new SimpleDateFormat("HH:mm:ss:SSS").format(new Date())+"结束");
            }
            catch(InterruptedException e) {
                e.printStackTrace();
            }

        });
        Thread.State state = runnable.getState();
        System.out.println(state+"----"+new SimpleDateFormat("HH:mm:ss:SSS").format(new Date()));
        runnable.start();
        state=runnable.getState();
        System.out.println(state+"----"+new SimpleDateFormat("HH:mm:ss:SSS").format(new Date()));
        do {
            state = runnable.getState();//更新state状态
            System.out.println(state+"----"+new SimpleDateFormat("HH:mm:ss:SSS").format(new Date()));

        }while(state!=Thread.State.TERMINATED);

    }
}