线程生命周期中的六种状态

线程的六种状态分别是:  NEW RUNNABLE TERMINATED   TIMED_WAITING BLOCKED WAITING

NEW: 表示线程已经创建成功,但是没有启动: 

RUNNABLE: 表示线程已经在运行或者正在等待CPU分配资源

TERMINATED: 表示run方法执行完毕

TIMED_WAITING: 表示陷入了又时间限制的等待序列中,比如: Thread.sleep(2000);

BLOCKED: 线程阻塞,比如:  synchronized 加锁

WAITING : 表示没有限制的睡眠或者等待

下面示例:

/**
 * <Description>
 * 线程 NEW RUNNABLE TERMINATED 三种状态展示
 */
public class StatusThread implements Runnable {
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println(i);
        }
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new StatusThread());
        System.out.println(thread.getState());
        thread.start();
        System.out.println(thread.getState());
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(thread.getState());

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(thread.getState());

    }
}
/**
 * <Description>
 * 线程 TIMED_WAITING BLOCKED WAITING 三种状态展示
 */
public class StatusThread2 implements Runnable {


    private synchronized void syn(){
        System.out.println(Thread.currentThread().getName());
        try {
            Thread.sleep(2000);
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        StatusThread2 statusThread2 = new StatusThread2();
        Thread thread1 = new Thread(statusThread2);
        thread1.start();
        Thread thread2 = new Thread(statusThread2);
        thread2.start();
        Thread.sleep(10);
        System.out.println(thread1.getState());
        System.out.println(thread2.getState());
        Thread.sleep(2300);
        System.out.println(thread1.getState());
    }

    public void run() {
        syn();
    }
}
发布了60 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_42214548/article/details/103888491