zoukankan      html  css  js  c++  java
  • 并发和多线程(二)--启动和中断线程(Interrupt)的正确姿势

    启动线程:

      从一个最基本的面试题开始,启动线程到底是start()还是run()?

    Runnable runnable = () -> System.out.println(Thread.currentThread().getName());
    Thread thread = new Thread(runnable);
    thread.run();
    thread.start();
    结果:
    main
    Thread-0

      我们可以看到thread.run()是通过main线程执行的,而start()启动的才是一个新线程。run()只是在线程启动的时候进行回调而已,如果没有start(),run()也只是一个普通方法。

      start()方法不一定直接启动新线程,而是请求jvm在空闲的时候去启动,由线程调度器决定。

    思考题:如果重复执行start()方法会怎样?

    Runnable runnable = () -> System.out.println(Thread.currentThread().getName());
    Thread thread = new Thread(runnable);
    thread.start();
    thread.start();
    结果:
    Exception in thread "main" Thread-0
    java.lang.IllegalThreadStateException
    at java.lang.Thread.start(Thread.java:705)
    at com.diamondshine.Thread.ThreadClass.main(ThreadClass.java:33)

    重复执行start()会出现异常,可以从start()的源码得到,因为启动线程的时候,会检测当前线程状态

    public synchronized void start() {
        
        if (threadStatus != 0)    //判断线程启动时的状态是否为new,如果不是,直接抛出异常
            throw new IllegalThreadStateException();
    
        group.add(this);
    
        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
    
            }
        }
    }
    View Code

    PS:关于run()对应Thread和Runnable的区别,请参考上一篇博客并发和多线程(一)--创建线程的方式

    线程停止

      相比线程启动,线程停止要复杂很多,有些方式虽然可以正常使用,但是可能存在某些风险,也是我们需要深入学习的地方。

    1、stop、suspend、resume

      这三种方式一般来说不会对我们有影响,因为是已废弃的方法,官方不推荐使用

    stop():

      废弃的原因,可以查看:https://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html

    PS:stop执行之后,会释放monitor的锁,而不是像某些并发书里面写的不释放锁,参考上面的文档。

    suspend和resume:

      是配套使用的,suspend本身不释放锁进行休眠,等待resume唤醒,这样很容易满足死锁的条件,所以官方不推荐使用。

    2、Interrupt()

      我们中断一个线程通常使用Interrupt(),官方废弃stop(),推荐的也是通过Interrupt()实现线程中断。Interrupt()的特点是通知中断线程,而这个线程是否中断选择权在于其本身,这是官方开发人员设计思想:需要被停止的线程可能不是你写的,对其了解可能不够,所以讲是否中断的选择权交于其本身,Interrupt()只是改变中断位的状态。

      中断线程的代码书写,取决于线程运行的方式,所以我们可以分类进行分析处理。

    2.1).一般情况

      一般情况是指,没有调用sleep()、wait()等阻塞状态下的中断。

    public static void main(String[] args){
        Runnable runnable = () -> {
            int num = 0;
            while (num <= Integer.MAX_VALUE / 10) {
                if (num % 1000 == 0) {
                    log.info("{}为1000的倍数", num);
                }
                num++;
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.interrupt();
    }
    View Code
    结果:最后一行
    [Thread-0] INFO com.diamondshine.Thread.ThreadClass - 214748000为1000的倍数

      从结果上看,interrupt()并没有 让线程停止,因为Integer的最大值2147483647

     正确的代码应该是:

    public static void main(String[] args){
        Runnable runnable = () -> {
            int num = 0;
            while (!Thread.currentThread().isInterrupted() && num <= Integer.MAX_VALUE / 10) {
                if (num % 1000 == 0) {
                    log.info("{}为1000的倍数", num);
                }
                num++;
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread.interrupt();
    }
    View Code
    结果:最后一行
    [Thread-0] INFO com.diamondshine.Thread.ThreadClass - 96540000为1000的倍数

       通过结果知道,成功中断了线程。通过isInterrupted()的判断让线程提前中断了,所以interrupt()的作用只是将Interrupted标志位置为true。

    2.2).线程处于阻塞状态

    public static void main(String[] args) throws InterruptedException{
        Runnable runnable = () -> {
            int num = 0;
            try {
                while (!Thread.currentThread().isInterrupted() && num <= 100) {
                    if (num % 100 == 0) {
                        log.info("{}为100的倍数", num);
                    }
                    num++;
                }
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        Thread.sleep(5000);
        thread.interrupt();
    }
    View Code
    结果:
    16:24:44.403 [Thread-0] INFO com.diamondshine.Thread.ThreadClass - 942000为1000的倍数
    java.lang.InterruptedException: sleep interrupted
        at java.lang.Thread.sleep(Native Method)
        at com.diamondshine.Thread.ThreadClass.lambda$main$0(ThreadClass.java:28)
        at java.lang.Thread.run(Thread.java:745)

      主线程sleep休眠5000ms,然后执行interrupt(),而Thread-0只是执行代码时间很短,然后进入sleep,最后出现异常,程序停止运行。所以处于sleep阻塞状态下,可以自动通过抛出异常来相应interrupt(),然后try catch进行捕获异常。

     2.3).线程每次迭代都进行阻塞

    public static void main(String[] args) throws InterruptedException{
        Runnable runnable = () -> {
            int num = 0;
            try {
                while (num <= Integer.MAX_VALUE) {
                    if (num % 100 == 0) {
                        log.info("{}为100的倍数", num);
                    }
                    num++;
                    Thread.sleep(1);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        Thread.sleep(500);
        thread.interrupt();
    }
    View Code
    结果:
    20:26:15.870 [Thread-0] INFO com.diamondshine.Thread.ThreadClass - 0为100的倍数
    20:26:16.060 [Thread-0] INFO com.diamondshine.Thread.ThreadClass - 100为100的倍数
    20:26:16.254 [Thread-0] INFO com.diamondshine.Thread.ThreadClass - 200为100的倍数
    java.lang.InterruptedException: sleep interrupted
        at java.lang.Thread.sleep(Native Method)
        at com.diamondshine.Thread.ThreadClass.lambda$main$0(ThreadClass.java:24)
        at java.lang.Thread.run(Thread.java:745)

      从上面代码可以看到,在每次迭代都阻塞的场景下,即使没有使用isInterrupted()判断,通过sleep对interrupt()方法做出响应,也可以实现线程中断。

    sleep自动清除中断信号

    public static void main(String[] args) throws InterruptedException{
        Runnable runnable = () -> {
            int num = 0;
                while (num <= Integer.MAX_VALUE) {
                    if (num % 100 == 0) {
                        log.info("{}为100的倍数", num);
                    }
                    num++;
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        Thread.sleep(500);
        thread.interrupt();
    }
    View Code
    结果:
    20:34:40.499 [Thread-0] INFO com.diamondshine.Thread.ThreadClass - 100为100的倍数 20:34:40.701 [Thread-0] INFO com.diamondshine.Thread.ThreadClass - 200为100的倍数 java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at com.diamondshine.Thread.ThreadClass.lambda$main$0(ThreadClass.java:24) at java.lang.Thread.run(Thread.java:745) 20:34:40.897 [Thread-0] INFO com.diamondshine.Thread.ThreadClass - 300为100的倍数 20:34:41.091 [Thread-0] INFO com.diamondshine.Thread.ThreadClass - 400为100的倍数 20:34:41.283 [Thread-0] INFO com.diamondshine.Thread.ThreadClass - 500为100的倍数

      我们改变了try catch的位置,发现sleep响应interrupt抛出异常之后,程序继续执行。这是因为抛出的异常被catch住了,但是while循环还是继续的。这种情况下怎么解决呢?尝试在while循环加上对interrupt标志位判断。

    public static void main(String[] args) throws InterruptedException{
        Runnable runnable = () -> {
            int num = 0;
                while (!Thread.currentThread().isInterrupted() && num <= Integer.MAX_VALUE) {
                    if (num % 100 == 0) {
                        log.info("{}为100的倍数", num);
                    }
                    num++;
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        Thread.sleep(500);
        thread.interrupt();
    }
    View Code

      结果和上面一样,sleep响应interrupt,但是程序还是继续执行,原因就是因为当线程在sleep过程中相应中断,会自动清除中断标志位,所以这是一种错误的写法。

    线程中断的最佳实践

      在项目开发中,一般不会像上面直接在Runnable中通过lamdba写逻辑,因为逻辑没有这么简单,可能会在run()中调用方法,这时候就需要注意代码的书写,一般有两种方式。

    1、传递中断信息

    错误的方式:

    private static void doSomething() {
        try {
            //do something
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) throws InterruptedException{
        Runnable runnable = () -> {
                while (true) {
                    //do something
                    System.out.println("continue");
                    doSomething();
                }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        Thread.sleep(500);
        thread.interrupt();
    }
    View Code
    结果:
    continue
    continue
    java.lang.InterruptedException: sleep interrupted
        at java.lang.Thread.sleep(Native Method)
        at com.diamondshine.Thread.ThreadClass.doSomething(ThreadClass.java:18)
        at com.diamondshine.Thread.ThreadClass.lambda$main$0(ThreadClass.java:28)
        at java.lang.Thread.run(Thread.java:745)
    continue
    continue 

      这种方式,在方法内部吃掉异常,导致外层调用这个方法,无法终止线程。

    正确写法:throws向上抛出异常,将interrupt传递出去。

    正确做法:
    private static void doSomething() throws InterruptedException{
        //do something
        Thread.sleep(1000);
    }
    
    public static void main(String[] args) throws InterruptedException{
        Runnable runnable = () -> {
            try {
                while (true) {
                    //do something
                    System.out.println("continue");
                    doSomething();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        Thread.sleep(500);
        thread.interrupt();
    }
    View Code

    2、恢复中断

     如果不想传递中断,就只能采用这种方式,代码如下。

    private static void doSomething(){
        try {
            //do something
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        //在sleep响应中断时候,重新恢复中断信息
            Thread.currentThread().interrupt();
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) throws InterruptedException{
        Runnable runnable = () -> {
            int num = 0;
            while (num <= 10000) {
                if (!Thread.currentThread().isInterrupted()) {
                    //do something
                    System.out.println("continue");
                    break;
                }
                doSomething();
                num++;
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        Thread.sleep(500);
        thread.interrupt();
    }
    View Code

    在catch代码块中重新恢复中断信息,然后通过 isInterrupted()判断状态,然后break跳出循环。

    我们前面演示了sleep响应中断,除了sleep(),还有很多方法可以做到:

    wait()、join()、BlockingQueue.take()/put()、Lock.lockInterruptibly()、CountdownLatch、CyclicBarrier、Exchange、nio。

    使用Interrupt的好处:

    1、使用interrupt中断线程不是强制性的,相对比较安全。

    2、想停止线程,要请求方、被停止方、子方法被调用方相互配合才行。

    2.1).请求方:

      发出中断信号。

    2.2).被停止方:

      在合适的时候检查中断信号,并且可能抛出InterrupedException的地方处理该中断信号。

    2.3).子方法被调用方:

      优先在方法层面抛出InterrupedException,或者检查到中断信号时,再次设置中断状态。

    3、volatile实现线程中断

    @Slf4j
    public class ThreadClass implements Runnable{
    
        //创建volatile修饰的变量
        private volatile boolean flag = false;
    
        @Override
        public void run() {
            int num = 0;
            try {
                while (!flag && num <= 10000) {    //通过volatile的可见性实现线程中断
                    if (num % 100 == 0) {
                        log.info("{}为100的倍数", num);
                    }
                    Thread.sleep(1);
                    num++;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        public static void main(String[] args) throws InterruptedException{
            ThreadClass threadClass = new ThreadClass();
            Thread thread = new Thread(threadClass);
            thread.start();
            Thread.sleep(500);
            threadClass.flag = true;
        }
    
    }
    View Code
    结果:
    13:47:14.660 [Thread-0] INFO com.diamondshine.Thread.ThreadClass - 0为100的倍数
    13:47:14.858 [Thread-0] INFO com.diamondshine.Thread.ThreadClass - 100为100的倍数
    13:47:15.027 [Thread-0] INFO com.diamondshine.Thread.ThreadClass - 200为100的倍数

      从上面结果看,通过volatile的可见性同样实现了线程中断(关于可见性,可以查看JMM和线程安全三大特性相关内容)

    volatile实现线程中断的限制

      长时间阻塞的场景下,volatile是无法中断线程的,例如使用wait()或者阻塞队列。如果现在有个生产者消费者场景,生产者生产的很快,但是消费者消费速度不够,如果Consumer不需要更多的,请求Producer终止线程,这个场景应该是很有可能出现的。

    @Slf4j
    public class ThreadClass{
    
        public static void main(String[] args) throws InterruptedException{
            ThreadClass threadClass = new ThreadClass();
            ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<>(10);
            Producer producer = threadClass.new Producer(queue);
            Thread thread = new Thread(producer);
            thread.start();
            Thread.sleep(1000);
    
            Consumer consumer = threadClass.new Consumer(queue);
            while (consumer.needMoreNums()) {   //通过这个方法模拟需要进行Producer限流
                log.info("{}被消费了", consumer.blockingQueue.take());
                Thread.sleep(100);  //每次消费sleep 100ms,模拟Consumer消费慢的场景
            }
            System.out.println("消费者不需要更多数据了。");
    
            //一旦消费不需要更多数据了,我们应该让生产者也停下来,但是实际情况
            producer.flag=true;
            log.info("{}", producer.flag);
    //        thread.interrupt();
        }
    
        class Producer implements Runnable{
    
            private volatile boolean flag = false;
    
            private ArrayBlockingQueue blockingQueue;
    
            public Producer(ArrayBlockingQueue blockingQueue) {
                this.blockingQueue = blockingQueue;
            }
    
            @Override
            public void run() {
                int num = 0;
                try {
                    while (!flag && num <= 10000) {
                        if (num % 100 == 0) {
                            blockingQueue.put(num); //最终Thread-0会被阻塞在这里
                            log.info("{}被放入生产者队列", num);
                        }
                        num++;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    log.info("生产者运行结束");
                }
            }
        }
        class Consumer{
    
            private ArrayBlockingQueue blockingQueue;
    
            public Consumer(ArrayBlockingQueue blockingQueue) {
                this.blockingQueue = blockingQueue;
            }
    
            //通过needMoreNums模拟消费者限流的情况
            public boolean needMoreNums() {
                if (Math.random() > 0.95) {
                    return false;
                }
                return true;
            }
        }
    }
    生产者-消费者场景-volatile中断线程

    结果:

       从结果看,Consumer消费太慢,导致Producer阻塞在blockingQueue.put(),这时候无法通过while检测状态,但是interrupt就可以解决这个场景。

    @Slf4j
    public class ThreadClass{
    
        public static void main(String[] args) throws InterruptedException{
            ThreadClass threadClass = new ThreadClass();
            ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<>(10);
            Producer producer = threadClass.new Producer(queue);
            Thread thread = new Thread(producer);
            thread.start();
            Thread.sleep(1000);
    
            Consumer consumer = threadClass.new Consumer(queue);
            while (consumer.needMoreNums()) {   //通过这个方法模拟需要进行Producer限流
                log.info("{}被消费了", consumer.blockingQueue.take());
                Thread.sleep(100);  //每次消费sleep 100ms,模拟Consumer消费慢的场景
            }
            System.out.println("消费者不需要更多数据了。");
    
            //一旦消费不需要更多数据了,我们应该让生产者也停下来,但是实际情况
            thread.interrupt(); //通过interrupt中断线程
        }
    
        class Producer implements Runnable{
    
            private volatile boolean flag = false;
    
            private ArrayBlockingQueue blockingQueue;
    
            public Producer(ArrayBlockingQueue blockingQueue) {
                this.blockingQueue = blockingQueue;
            }
    
            @Override
            public void run() {
                int num = 0;
                try {
                    while (!Thread.currentThread().isInterrupted() && num <= 10000) {
                        if (num % 100 == 0) {
                            blockingQueue.put(num); //最终Thread-0会被阻塞在这里
                            log.info("{}被放入生产者队列", num);
                        }
                        num++;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    log.info("生产者运行结束");
                }
            }
        }
        class Consumer{
    
            private ArrayBlockingQueue blockingQueue;
    
            public Consumer(ArrayBlockingQueue blockingQueue) {
                this.blockingQueue = blockingQueue;
            }
    
            //通过needMoreNums模拟消费者限流的情况
            public boolean needMoreNums() {
                if (Math.random() > 0.95) {
                    return false;
                }
                return true;
            }
        }
    }
    生产者-消费者-interrupt中断线程
    结果:
    14:56:11.562 [main] INFO com.diamondshine.Thread.ThreadClass - 2100被消费了
    14:56:11.562 [Thread-0] INFO com.diamondshine.Thread.ThreadClass - 3100被放入生产者队列
    java.lang.InterruptedException
        at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.reportInterruptAfterWait(AbstractQueuedSynchronizer.java:2014)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2048)
        at java.util.concurrent.ArrayBlockingQueue.put(ArrayBlockingQueue.java:353)
        at com.diamondshine.Thread.ThreadClass$Producer.run(ThreadClass.java:52)
        at java.lang.Thread.run(Thread.java:745)
    消费者不需要更多数据了。
    14:56:11.663 [Thread-0] INFO com.diamondshine.Thread.ThreadClass - 生产者运行结束

      jvm设计人员考虑到长时间阻塞的场景,通过interrupt照样可以解决,抛出异常,相应阻塞。这里Thread.currentThread().isInterrupted()替代flag,没有也是可以的,因为是通过抛出异常响应的中断。

    总结:

      如果我们遇到了线程长时间阻塞(很常见的情况),volatile就没办法及时唤醒它,或者永远都无法唤醒该线程,而interrupt设计之初就是把wait等长期阻塞作为一种特殊情况考虑在内了,我们应该用interrupt思维来停止线程。

      interrupt对应的native方法,Thread.sleep() 、lockSupport.park()、 Synchronized同步块、Object.wait()等都可以做出中断相应。

    判断中断状态:

     interrupted():

      static方法,只关注哪个类执行interrupted()这行代码,而和*.interrupted()的这个*没有关系,返回Interrupt状态,但是会把状态位ClearInterrupted置为false,自动清除状态。

    isInterruped():

      返回Interrupt状态。

    public static void main(String[] args) throws InterruptedException{
        Thread threadOne = new Thread(() -> {
            while (true) {
                
            }
        });
    
        // 启动线程
        threadOne.start();
        //设置中断标志
        threadOne.interrupt();
        //获取中断标志
        System.out.println("isInterrupted: " + threadOne.isInterrupted());
        //获取中断标志并重置
        System.out.println("isInterrupted: " + threadOne.interrupted());
        //获取中断标志并重置
        System.out.println("isInterrupted: " + Thread.interrupted());
        //获取中断标志
        System.out.println("isInterrupted: " + threadOne.isInterrupted());
    
        System.out.println("Main thread is over.");
    }
    View Code
    isInterrupted: true
    isInterrupted: false
    isInterrupted: false
    isInterrupted: true
    Main thread is over.
    结果

      先思考一下,再看一下结果,和你想的是否一致,如果真的理解了这两个方法,这段代码运行结果应该很容易理解。

    思考题:

    如何处理不可中断阻塞?
    A. 用interrupt方法来请求停止线程 
    B. 不可中断的阻塞无法处理 
    C. 根据不同的类调用不同的方法
    答案:C

      如果线程阻塞是由于调用了 wait(),sleep() 或 join() 方法,可以中断线程,通过抛出InterruptedException异常来唤醒该线程相应阻塞。 对于不能响应InterruptedException的阻塞,并没有一个通用的解决方案。 但是我们可以利用特定的其它的可以响应中断的方法,比如ReentrantLock.lockInterruptibly,比如关闭套接字使线程立即返回等方法来达到目的。因为有很多原因会造成线程阻塞,所以针对不同情况,唤起的方法也不同。

    总结:

    interrupt这部分内容比较多吧,如果感觉有帮助,需要多想想,下面是基本总结,如果看着这些能想到对应的内容,那说明掌握的不错。

    启动线程start()和run()

    多次执行start()的结果

    停止线程

    1、stop、suspend、resume 不推荐

    2、interrupt()

    多种情况下的中断,一般场景,阻塞状态下,每次遍历都阻塞

    sleep、wait等阻塞状态下,对interrupt的响应,而且会直接清除中断信号

    最佳实践

    1、传递中断

    2、恢复中断

    3、volatile实现

    一般场景可以实现

    长时间阻塞,volatile无法实现中断,interrupt可以满足这个场景

    判断线程中断的两个方法

    interrupted()

    isInterruped()

  • 相关阅读:
    Gym 100801D Distribution in Metagonia (数学思维题)
    Gym 100801E Easy Arithmetic (思维题)
    GNOME编辑器--gedit 构建基本脚本
    linux默认编辑器 sublime
    su和su-命令的本质区别
    #ifdef #ifndef使用
    linux 安装软件程序
    linux命令行与shell脚本编程大全---更多bash shell命令
    预处理语句--#define、#error和#warning
    FW开发代码规范---小任性(2)
  • 原文地址:https://www.cnblogs.com/huigelaile/p/11715172.html
Copyright © 2011-2022 走看看