JAVA线程的生命周期

线程的生命周期

Java线程既然能够创建,那么也势必会被销毁,所以线程是存在生命周期的,那么我们接下来从线程的生命周期开

始去了解线程。

State一共有6种状态(NEW、RUNNABLE、BLOCKED、WAITING、TIME_WAITING、TERMINATED

public enum State {
        /**
         * Thread state for a thread which has not yet started.
         */
        NEW,

        /**
         * Thread state for a runnable thread.  A thread in the runnable
         * state is executing in the Java virtual machine but it may
         * be waiting for other resources from the operating system
         * such as processor.
         */
        RUNNABLE,

        /**
         * Thread state for a thread blocked waiting for a monitor lock.
         * A thread in the blocked state is waiting for a monitor lock
         * to enter a synchronized block/method or
         * reenter a synchronized block/method after calling
         * {@link Object#wait() Object.wait}.
         */
        BLOCKED,

        /**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the
         * following methods:
         * <ul>
         *   <li>{@link Object#wait() Object.wait} with no timeout</li>
         *   <li>{@link #join() Thread.join} with no timeout</li>
         *   <li>{@link LockSupport#park() LockSupport.park}</li>
         * </ul>
         *
         * <p>A thread in the waiting state is waiting for another thread to
         * perform a particular action.
         *
         * For example, a thread that has called <tt>Object.wait()</tt>
         * on an object is waiting for another thread to call
         * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
         * that object. A thread that has called <tt>Thread.join()</tt>
         * is waiting for a specified thread to terminate.
         */
        WAITING,

        /**
         * Thread state for a waiting thread with a specified waiting time.
         * A thread is in the timed waiting state due to calling one of
         * the following methods with a specified positive waiting time:
         * <ul>
         *   <li>{@link #sleep Thread.sleep}</li>
         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
         *   <li>{@link #join(long) Thread.join} with timeout</li>
         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
         * </ul>
         */
        TIMED_WAITING,

        /**
         * Thread state for a terminated thread.
         * The thread has completed execution.
         */
        TERMINATED;
    }

NEW:初始状态,线程被构建,但是还没有调用start()方法

RUNNABLE:可运行,java虚拟机已经运行,还在等待OS分配CPU资源执行

BLOCKED:阻塞状态,1.一个正在阻塞等待一个监视器锁的线程处于这一状态,2.调用Thread.wait()后被notify/notifyall 再次进入(reenter)同步块。BLOCKED 状态可以视作为一种特殊的 WAITING,是传统 WAITING(调用Object#wait(),#join() ,LockSupport#park())状态的一个细分,阻塞也分为几种情况:

➢等待阻塞:运行的线程执行wait()方法,jvm会把当前线程放入到等待队列

➢同步阻塞:运行的线程在获取对象的同步锁时,若该同步锁被其他线程锁占用了,那么jvm会把当前的线程放入到锁池中

➢其他阻塞:运行的线程执行Thread.sleep()或者t.join()方法,或者发出了I/O请求时,JVM会把当前线程设置为阻塞状态,当sleep()结束、join()线程终止、io处理完毕则线程恢复

TIME_WAITING:超时等待状态,超时以后自动返回,调用Thread.sleep,Object#wait(long), #join(long) ,LockSupport.parkNanos,LockSupport.parkUntil

TERMINATED:终止状态,表示当前线程执行完毕。

线程状态转化

在这里插入图片描述

通过代码演示线程状态
TIME_WAITING
//TIME_WAITING
new Thread(() -> {
    while (true) {
        System.out.println(Thread.currentThread().getName() + "->执行了run()");
        try {
            TimeUnit.SECONDS.sleep(88);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}, "thread-time-waiting").start();

在这里插入图片描述

WAITING
//WAITING,线程在ThreadStatus类锁上通过wait进行等待
new Thread(() -> {
    while (true) {
        synchronized (ThreadStatus.class){
            System.out.println(Thread.currentThread().getName() + "->before wait()");
            try {
                ThreadStatus.class.wait();
                System.out.println(Thread.currentThread().getName() + "->after wait()");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}, "thread-waiting").start();
//WAITING,t线程执行join(),main线程等待
Thread t = new Thread(()->{
    System.out.println("exec thread-sleep ...");
    try {
        TimeUnit.SECONDS.sleep(100);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
});
t.start();
System.out.println("before thread-sleep join()");
try {
    t.join();
} catch (InterruptedException e) {
    e.printStackTrace();
}
System.out.println("after thread-sleep join()");
System.out.println("complete main() ");

在这里插入图片描述

// BLOCKED t1 和 t2争夺锁,造成一个线程阻塞
new Thread(()->{
    synchronized (ThreadStatus.class){
        while(!Thread.currentThread().isInterrupted()){

        }
    }
},"t1").start();
new Thread(()->{
    synchronized (ThreadStatus.class){
        while(!Thread.currentThread().isInterrupted()){

        }
    }
},"t2").start();

在这里插入图片描述

源码地址

git@gitlab.com:cuim1/test-demo.git
https://gitlab.com/cuim1/test-demo.git

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值