线程的状态及线程的中止方式

线程状态

此处以java.lang.Thread.State类中的6个状态分别说明,查看State类简介:

A thread state. A thread can be in one of the following states:
一个线程的状态,可以是以下状态之一:

NEW : A thread that has not yet started is in this state.
尚未启动的线程的状态。

RUNNABLE: A thread executing in the Java virtual machine is in this state.
可运行线程的状态,等待CPU调度。

BLOCKED: A thread that is blocked waiting for a monitor lock is in this state.
阻塞状态,线程阻塞等待监视器锁定的线程状态,处于synchronized同步代码块或方法中被阻塞。

WAITING: A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
等待状态,不带超时的方式:Object.wait、Thread.join、LockSupport.park。

TIMED_WAITING: A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
带一定时间的等待,带超时的方式:Thread.sleep、Object.wait、Thread.join LockSupport.parkNanos、LockSupport.parkUntil。

TERMINATED: A thread that has exited is in this state.
终止线程的状态,线程正常完成执行,或出现异常。

线程间状态的转换如下图所示:

在这里插入图片描述

线程中止

在这里插入图片描述
stop() 和interrupt() 方式比较:
stop(): 强制中止线程,并且清除监控器锁(synchronized,lock)的消息,可能会导致线程安全问题。

interrupt():能够正确中止程序,并且不会在同步代码块中出现线程安全问题。

标志位实现代码中止

public class ManualStop {

	/* 标志位 */
    volatile static boolean flag = true;

    public static void main(String[] args) throws InterruptedException {

        new Thread(() -> {
            try {
                while (flag) { // 判断是否运行
                    System.out.println("运行中");
                    Thread.sleep(1000L);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        Thread.sleep(3000L);
        flag = false;
        System.out.println("程序运行结束~");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值