zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【多线程】Thread的interrupt()

多线程 thread interrupt
2023-09-14 09:04:52 时间

一、前言

    如果子线程执行完毕终止状态,主线程再去调用interrupt()有什么效果?如果子线程还在执行过程中,主线程调用interrupt()有什么结果?

二、模拟实验

1、模拟子线程执行完毕再调用interrupt()

​
public class Test {
    
    public static void main(String[] args) throws InterruptedException {
        test2();
    }

    private static void test2() throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                log.info("1前{}", Thread.currentThread().getName());
                // 导致当前正在执行的线程休眠(暂时停止执行)指定的毫秒数,这取决于系统计时器和调度器
                // 的准确与精密。线程不会丢失任何监视器的所有权。
                Thread.sleep(2000);
                log.info("1后{}", Thread.currentThread().getName());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        log.info("2前{}", Thread.currentThread().get