第五章:LockSupport与线程中断

阿里蚂蚁金服面试题

image-20221121221608262

  • 三个方法了解过吗?用在哪?
  • 如何停止一个运行中的线程?
  • 如何中断一个运行中的线程??

什么是线程中断机制?

首先

一个线程不应该由其他线程来强制中断或停止,而是应该由线程自己自行停止。

所以,Thread.stop, Thread.suspend, Thread.resume 都已经被废弃了。

其次

在Java中没有办法立即停止一条线程,然而停止线程却显得尤为重要,如取消一个耗时操作。

因此,Java 提供了一种用于停止线程的协商机制——中断

中断只是一种协作协商机制,Java没有给中断增加任何语法,中断的过程完全需要程序员自己实现。若要中断一个线程,你需要手动调用该线程的 interrupt 方法,该方法也仅仅是将线程对象的中断标识设成true;接着你需要自己写代码不断地检测当前线程的标识位,如果为true,表示别的线程要求这条线程中断,此时究竟该做什么需要你自己写代码实现。

每个线程对象中都有一个标识,用于表示线程是否被中断;该标识位为true表示中断,为false表示未中断;

通过调用线程对象的interrupt方法将该线程的标识位设为true;可以在别的线程中调用,也可以在自己的线程中调用。

中断相关的 API 方法

方法描述
public void interrupt()实例方法,实例方法interrupt()仅仅是设置线程的中断状态为true,发起一个协商而不会立刻停止线程
public static boolean interrupted()静态方法,Thread.interrupted();判断线程是否被中断,并清除当前中断状态 这个方法做了两件事:1、返回当前线程的中断状态 2 、将当前线程的中断状态设为false(这个方法有点不好理解,因为连续调用两次的结果可能不一样。
public boolean isInterrupted()实例方法,判断当前线程是否被中断(通过检查中断标志位)

面试题

通过面试演示三个API的使用方法以及注意事项

1、如果停止正在运行的一个线程?

stopstop和suspend及resume一样都是过期作废的方法。因此不推荐使用

第一种方式,使用 volatile 中断线程

利用 volatile 的可见性,用于判断是否中断的一个标志位

public class interruptTest01 {
    // 标志位
    static volatile boolean isStop = false;
    public static void main(String[] args) {

        new Thread(() -> {
            while (true) {
                if (isStop) {
                    System.out.println(Thread.currentThread().getName()  +"\t" + "isStop 被修改为true,线程停止");
                    break;
                }
                System.out.println("hello, volatile....");
            }
        }, "t1").start();

        try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
        
        new Thread(() -> {
            isStop =  true;
        }, "t2").start();
    }
}

第二种方式:通过 AtomicBoolean 中断

  static AtomicBoolean atomicBoolean =  new AtomicBoolean(false);
    public static void main(String[] args) {

        new Thread(() -> {
            while (true) {
                if (atomicBoolean.get()) {
                    System.out.println(Thread.currentThread().getName()  +"\t" + "atomicBoolean 被修改为true,线程停止");
                    break;
                }
                System.out.println("hello, atomicBoolean....");
            }
        }, "t1").start();

        try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}

        new Thread(() -> {
            atomicBoolean.set(true);
        }, "t2").start();
    }

第三种方式:使用 Thread类 自带的 api 实现中断

   public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println(Thread.currentThread().getName() + "\t" + "interrupted 被修改为true,线程停止");
                    break;
                }
                System.out.println("hello, interrupted....");
            }
        }, "t1");
        t1.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            // 设置中断标志为 true
            t1.interrupt();
        }, "t2").start();

    }

2 当前线程的中断标识为true,是不是线程就立刻停止?

不是

案例一
  • 如果线程处于正常活动状态,那么会将该线程的中断标志设置为 true,仅此而已。被设置中断标志的线程将继续正常运行,不受影响。所以, interrupt() 并不能真正的中断线程,需要被调用的线程自己进行配合才行

  • 中断不活动的线程不会产生任何影响,看下面案例

public class InterruptTest02 {
    public static void main(String[] args) {
       Thread t1 =  new Thread(() -> {
           
            for (int i = 0; i < 100; i++) {
                System.out.println("----- " + i);
            }
           // true,虽然中断标志位为 true,但是并没中断线程
           System.out.println("第二次中断标志: " + Thread.currentThread().isInterrupted());
        }, "t1");
       t1.start();
        System.out.println("默认中断标志状态: " + t1.isInterrupted() ); //false
        // 将标志位设置为true
        t1.interrupt();
        try {Thread.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}
        System.out.println("第一次中断标志: " + t1.isInterrupted()); //true
        try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}
        // 由于线程 t1已结束,对于结束的线程,中断不会产生任何影响
        System.out.println("第三次中断标志: " + t1.isInterrupted()); // false
    }
}

输出结果

默认的中断标志为false

当设置中断标志为 true 时,线程并没有结束,因此中断需要线程配合

当线程结束,中断不会产生任何影响

默认中断标志状态: false
----- 0
----- 1
----- 2
----- 3
----- 4
----- 5
----- 6
----- 7
----- 8
----- 9
----- 10
----- 11
----- 12
----- 13
----- 14
----- 15
----- 16
----- 17
----- 18
----- 19
----- 20
----- 21
----- 22
----- 23
----- 24
----- 25
----- 26
----- 27
----- 28
----- 29
----- 30
----- 31
----- 32
----- 33
----- 34
----- 35
----- 36
----- 37
----- 38
----- 39
----- 40
----- 41
----- 42
----- 43
----- 44
----- 45
----- 46
----- 47
----- 48
----- 49
----- 50
----- 51
----- 52
----- 53
----- 54
----- 55
----- 56
----- 57
----- 58
----- 59
----- 60
----- 61
----- 62
第一次中断标志: true
----- 63
----- 64
----- 65
----- 66
----- 67
----- 68
----- 69
----- 70
----- 71
----- 72
----- 73
----- 74
----- 75
----- 76
----- 77
----- 78
----- 79
----- 80
----- 81
----- 82
----- 83
----- 84
----- 85
----- 86
----- 87
----- 88
----- 89
----- 90
----- 91
----- 92
----- 93
----- 94
----- 95
----- 96
----- 97
----- 98
----- 99
第二次中断标志: true
第三次中断标志: false

Process finished with exit code 0

案例二

如果线程处于被阻塞状态(例如处于sleep, wait, join 等状态),在别的线程中调用当前线程对象的interrupt方法,那么线程将立即退出被阻塞状态(中断状态将被清除),并抛出一 个InterruptedException异常。

public class InterruptTest03 {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("中断标志位被修改: " + Thread.currentThread().isInterrupted() + ",线程停止");
                    break;
                }
                try {Thread.sleep(20);} catch (InterruptedException e) {e.printStackTrace();}
                System.out.println("hello,interrupt");
            }
        }, "t1");
        t1.start();
        
        try {Thread.sleep(200);} catch (InterruptedException e) {e.printStackTrace();}
        t1.interrupt();
    }
}

输出结果:

6

从结果可以看出,当线程正处于 sleep 阻塞状态时,设置标志位为 true,会立刻打断阻塞状态,并抛出InterruptedException异常,最终要的是会导致线程处于死循环。因此想要避免死循环,需要在 catch 语句中再一次设置中断标志

image-20221122165836671

演示输出结果:

7

3、静态方法Thread.interrupted(),谈谈你的理解

Thread.interrupted() 会做俩件事请:

  • 返回当前线程的中断标志位的状态
  • 将标志位设置成 false
public class InterruptTest04 {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName()+ "\t" + Thread.interrupted()); // false
        System.out.println(Thread.currentThread().getName()+ "\t" + Thread.interrupted());// false

        // 设置标志位为 true
        Thread.currentThread().interrupt();

        System.out.println(Thread.currentThread().getName()+ "\t" + Thread.interrupted());// true
        System.out.println(Thread.currentThread().getName()+ "\t" + Thread.interrupted());// false
    }
}

总结

  1. interrupt 方法仅仅是设置当前线程中断标志位为 true,并不会主动中断线程,线程的中断还需要线程自己配合(程序员手动判断标志位进行中断)
  2. 处于正在活动的线程,interrupt 方法会将中断标志位设置成 true
  3. 对于不活动的线程(结束的线程),interrupt 方法并不会影响当前线程的中断标志
  4. 对于处在阻塞状态下的线程来说,执行 interrupt 方法会导致抛出 InterruptedException 异常,并且会导致死循环。因此线程中如果有阻塞的情况,一定要在catch语句块中再次调用 interrupt 方法

isInterrupted 和 interrupted 的区别?

  • interrupted 为静态方法
  • isInterrupted 仅仅返回当前线程的中断标志位状态,interrupted 不仅返回了中断标志位状态,还会将中断标志位设置成false

源码中的区别

image-20221122171555905

LockSupport

官方解释:用于创建锁和其他同步类的基本线程阻塞原语。

image-20221122203605468

核心 API

static voidpark() 禁止当前线程进行线程调度,除非许可证可用。
static void``unpark(Thread thread)为给定的线程提供许可证(如果尚未提供)。

阻塞、唤醒现成的三种方式

  1. 使用Object中的wait()方法让线程等待,使用Object中的notify()方法唤醒线程
  2. 使用 JUC 包中Conditionawait()方法让线程等待,使用signal()方法唤醒线程
  3. LockSupport类可以阻塞当前线程以及唤醒指定被阻塞的线程

使用 wait、notify 演示

使用 wait、notify 时的注意点

  • wait、notify 必须在同步代码块中或者 同步方法中使用,否则会报 IllegalMonitorStateException 异常
  • 在顺序上,一定是先 wait() ,在 notify()
  • 线程的锁对象、以及调用 wait、notify 的对象必须为同一个对象
public class WaitNotifyTest {
    public static void main(String[] args) {
        Object obj = new Object();
         new Thread(() -> {
            synchronized (obj) {
                System.out.println(Thread.currentThread().getName() + "  come in...");
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + "  end");
        }, "t1").start();

        try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
        new Thread(() -> {
            synchronized (obj) {
                System.out.println(Thread.currentThread().getName() + " 唤醒t1...");
                // 唤醒线程
                obj.notify();
            }
        }, "t2").start();
    }
}

使用 await、signal 演示

使用时的注意事项和wait notify 一样。

public class LockSupportTest01 {
    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        new Thread(() -> {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + "  come in...");
            try {
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            System.out.println(Thread.currentThread().getName() + "  end");
        }, "t1").start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " 唤醒t1...");
                // 唤醒线程
                condition.signal();
            } finally {
                lock.unlock();
            }
        }, "t2").start();
    }
}

以上俩种方式使用的局限性

  • 局限一:线程先要获得并持有锁,必须在锁块(synchronized或lock)中
  • 局限二:必须要先等待后唤醒,线程才能够被唤醒

因此衍生出了 park/unpark

park/unpark 实现阻塞/唤醒

通过park()和unpark(thread)方法来实现阻塞和唤醒线程的操作。

park 相当于 wait、await 方法 用来阻塞线程, unpark 相当于 notify、signal 方法 用来唤醒线程。

而 park/ unpark 与另外俩种方式的区别

  • park/ unpark 不会抛出异常,另外俩种方式会抛出 InterruptedException

  • park/ unpark 采用 Permit (许可证) 的方式来阻塞、唤醒线程,每个使用 LockSupport 的线程都有一个许可证

  • 调用一次 park 方法会消耗掉一张 许可证,因此当前线程会进入阻塞状态

  • unpark 会为指定的线程发放一张许可证,如果线程处于阻塞状态,会将线程唤醒。无论调用多少次,只会发放一张许可证

LockSupport 和 Semaphore 不同的是,LockSupport 的许可证只有一张,无法累加。消耗完就会被阻塞。

代码演示一

我们可以看到,park、unpark 并没在同步块中使用,LockSupport 并没有范围的局限性。

public class LockSupportTest01 {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            
            System.out.println(Thread.currentThread().getName() + " come in...");
            // 消耗许可证
            LockSupport.park();
            System.out.println(Thread.currentThread().getName() + "  end...");

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

		try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " 为 t1 发放许可证...");
            // 发放许可证
            LockSupport.unpark(t1);

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

代码演示二:、

park、unpark 并没有执行顺序的问题,也就是先唤醒在阻塞也不会出现 IllegalMonitorStateException 异常。

public class LockSupportTest01 {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}
            System.out.println(Thread.currentThread().getName() + " come in...");
            // 消耗许可证
            LockSupport.park();
            System.out.println(Thread.currentThread().getName() + "  end...");

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


        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " 为 t1 发放许可证...");
            // 发放许可证
            LockSupport.unpark(t1);

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

输出结果:

8

代码演示三

演示许可证的唯一性

消耗三张许可证,而 无论调用多少次 unpark 都只会发放一张许可证。 因此许可证不够,线程进入阻塞状态

public class LockSupportTest01 {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}
            System.out.println(Thread.currentThread().getName() + " come in...");
            // 消耗许可证
            LockSupport.park();
            LockSupport.park();
            LockSupport.park();
            System.out.println(Thread.currentThread().getName() + "  end...");

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


        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " 为 t1 发放许可证...");
            // 发放许可证
            LockSupport.unpark(t1);
            LockSupport.unpark(t1);
            LockSupport.unpark(t1);

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

结果

image-20221122220508896



各位彭于晏,如有收获点个赞不过分吧…✌✌✌

Alt


扫码关注公众号 【我不是秃神】 回复 JUC 可下载 MarkDown 笔记

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鲨瓜2号

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值