java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java线程生命周期

Java线程生命周期图文详细讲解

作者:健鑫.

在java中,任何对象都要有生命周期,线程也不例外,它也有自己的生命周期。线程的整个生命周期可以分为5个阶段,分别是新建状态、就绪状态、运行状态、阻塞状态和死亡状态

线程的状态

New

Runnable

Blocked

Waiting

Timed Waiting

Terminated

代码演示

public class NewRunnableTerminated implements Runnable {
    public static void main(String[] args) {
        Thread thread = new Thread(new NewRunnableTerminated());
        // 打印线程状态
        // New
        System.out.println(thread.getState());
        thread.start();
        // Runnable
        System.out.println(thread.getState());
//        try {
//            Thread.sleep(100);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        // Runnable
        System.out.println(thread.getState());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // TERMINATED
        System.out.println(thread.getState());
    }
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            System.out.println(i);
        }
    }
}
/*
* NEW
RUNNABLE
RUNNABLE
* TERMINATED
* */
public class BlockWaitingTimedWaiting implements Runnable{
    public static void main(String[] args) {
        BlockWaitingTimedWaiting blockWaitingTimedWaiting = new BlockWaitingTimedWaiting();
        Thread thread1 = new Thread(blockWaitingTimedWaiting);
        thread1.start();
        Thread thread2 = new Thread(blockWaitingTimedWaiting);
        thread2.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(thread1.getState());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(thread2.getState());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(thread1.getState());
    }
    @Override
    public void run() {
        syn();
    }
    private synchronized void syn() {
        try {
            Thread.sleep(1000);
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
/*
* TIMED_WAITING
BLOCKED
WAITING
* */

阻塞状态

到此这篇关于Java线程生命周期图文详细讲解的文章就介绍到这了,更多相关Java线程生命周期内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文