Java并发编程|第二篇:线程生命周期

系列文章

1.线程的状态

jdk源码中Thread类中有个State的枚举类,表示线程运行中的所有状态
在这里插入图片描述

  • NEW

Thread state for a thread which has not yet started.
创建线程,但是还没start()启动

  • RUNNABLE

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.
线程处于可运行状态,不代表一定运行

  • BLOCKED

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
被 Monitor 锁阻塞,表示当前线程在同步锁的场景运作

  • WAITING

Thread state for a waiting thread.
线程等待状态

  • TIMED_WAITING

Thread state for a waiting thread with a specified waiting time.
线程等待状态带一个时间的条件

  • TERMINATED

Thread state for a terminated thread.
The thread has completed execution.
线程执行结束

2.线程生命周期

在这里插入图片描述

  • 1.线程创建
  • 2.start() 开始
  • 3.线程执行中,运行中会有很多中间状态(WAITING,TIME_WAITING,BLOCKED)
  • 4.线程执行完毕,终止

3.状态测试代码

import java.util.concurrent.TimeUnit;

public class ThreadStatusDemo {
    public static void main(String[] args) {
        new Thread(() -> {
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(100);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "Time_Waiting_Thread").start();

        new Thread(() -> {
            while (true) {
                synchronized (ThreadStatusDemo.class) {
                    try {
                        ThreadStatusDemo.class.wait();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "Waiting_Thread").start();

        new Thread(new BlockedDemo(),"Block01_Thread").start();
        new Thread(new BlockedDemo(),"Block02_Thread").start();
    }

    static class BlockedDemo extends Thread {
        @Override
        public void run() {
            synchronized (BlockedDemo.class) {
                while (true) {
                    try {
                        TimeUnit.SECONDS.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}

打开idea终端或者cmd
cd到classpath对应的目录下面(非必要)
输入jps命令,查看jvm相关进程
在这里插入图片描述
输入jstack 进程号,查看进程中线程的信息
在这里插入图片描述
在这里插入图片描述

4.线程终止

4.1 线程执行完成

线程中重写run()方法中的程序代码执行完毕,线程自动终止

4.2 interrupt

调用线程的interrupt方法
run方法中的while(!Thread.currentThread().isInterrupted())为死循环
调用thread.interrupt()修改Thread.currentThread().isInterrupted()的值跳出循环

import java.util.concurrent.TimeUnit;

public class InterrputDemo {

    private static int i;

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                i++;
            }
            System.out.println("i:" + i);
        });
        thread.start();
        TimeUnit.SECONDS.sleep(1);
        thread.interrupt();
    }
}

在这里插入图片描述

5.线程复位

5.1interrupted

import java.util.concurrent.TimeUnit;

public class ThreadResetDemo {
    //1.thread.interrupted
    //2.InterruptedException

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("before:" + Thread.currentThread().isInterrupted());
                    Thread.interrupted();//复位-回到初始状态
                    System.out.println("after:" + Thread.currentThread().isInterrupted());
                }
            }
        });
        thread.start();
        TimeUnit.SECONDS.sleep(2);
        thread.interrupt();
    }
}

在这里插入图片描述

5.2抛出异常

import java.util.concurrent.TimeUnit;

public class ThreadExceptionDemo {
    private static int i;

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    TimeUnit.SECONDS.sleep(2);//中断一个处于阻塞状态的线程 wait/join/queue.take
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                i++;
                System.out.println("i:" + i);
            }
            System.out.println("i:" + i);
        });
        thread.start();
        TimeUnit.SECONDS.sleep(1);
        thread.interrupt();

        System.out.println(thread.isInterrupted());
    }
}

线程终止thread.interrupt();导致抛出异常,线程并未停止,而是继续执行
在这里插入图片描述

6.参考

腾讯课堂->咕泡学院->mic老师->并发编程基础

7.系列链接

上一篇:Java并发编程|第一篇:线程初体验
下一篇:Java并发编程|第三篇:synchronized锁

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值