中断线程的方式

  • 利用变量标识, 结束循环 (循环条件返回 false, 结束正在执行循环的线程)
  • 利用 interrupt()isInterrupt()
  • 对于 sleep() wait() join() 的线程, 利用 interrupt() 让线程抛出 InterruptedException, 在 catch 块中处理
变量标识
// 匿名内部类使用局部变量时, 必须是 final, 否则编译报错
// 匿名内部类使用字段, 不需要 final
// 使用 volatile 修饰, 实现多线程间变量的可见性
volatile boolean loop = true;

/**
 * while Condition
 */
@Test
public void testWhileCondition() {
    // 这里由于 lambda 表达式引用外部变量时, 必须 final 类型
    Thread t = new Thread(() -> {
        while (loop) {
            System.out.println("线程执行中...");
        }
        System.out.println("线程执行结束...");
    });
    t.start();

    ThreadUtils.sleepQuietly(1);

    // 结束循环
    loop = false;

    ThreadUtils.sleepQuietly(2);

}
利用 interrupt() isInterrupted()
/**
 * interrupt() 方法是 实例方法
 * thread 调用 interrupt() 后, 该线程会抛出异常
 */
@Test
public void testInterrupted() {
    Thread t = new Thread(() -> {
        // interrupted() 静态方法: 表示被打断, 并且恢复标记位为正常
        while (!Thread.currentThread().isInterrupted()) {
            System.out.println("线程没有被打断...");
        }
        System.out.println("线程被打断了...");
    });

    // 线程启动之前, 调用 interrupt() 方法, 什么也不做

    // 启动线程
    t.start();

    ThreadUtils.sleepQuietly(1);

    // 调用 interrupt() 方法时, 该线程只有在处于阻塞状态  (sleep join wait) 时, 才会抛出 InterruptedException, 否则什么也不做
    t.interrupt();

    ThreadUtils.sleepQuietly(5);
}
利用 interrupt() InterruptedException
/**
 * interrupt() 方法是 实例方法
 * thread 调用 interrupt() 后, 该线程会抛出异常
 */
@Test
public void testInterrupt() {
    Thread t = new Thread(() -> {
        try {
            // isInterrupted() false 没有被打断
            System.out.println("开始 Thread.currentThread().isInterrupted() = " + Thread.currentThread().isInterrupted());
            System.out.println("开始睡眠 1s...");
            Thread.sleep(2000);
            System.out.println("睡眠结束...");
        } catch (Exception e) {
            // 当抛出 InterruptedException 异常时, 我们处理
            log.error(e.getMessage(), e);
            // todo
        }
    });

    // 线程启动之前, 调用 interrupt() 方法, 什么也不做

    // 启动线程
    t.start();

    ThreadUtils.sleepQuietly(1);

    // 调用 interrupt() 方法时, 该线程只有在处于阻塞状态  (sleep join wait) 时, 才会抛出 InterruptedException, 否则什么也不做
    t.interrupt();
    // 在调用完 interrupt() 后, 通过 isInterrupted() 判断线程是否被打断了 (即抛出 InterruptedException 异常)
    System.out.println("主线程 Thread.currentThread().isInterrupted() = " + t.isInterrupted());

    ThreadUtils.sleepQuietly(5);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值