zoukankan      html  css  js  c++  java
  • Java多线程中断知识

    多线程是并发执行的,如果我们想提前结束一个线程,或者想对一个正在运行的线程进行交互一会,我们需要用中断,即使是要停止也不能使用Stop。由于多线程任务是异步性的,强制停止这可能会引起程序的错误。

    中断其实是一个很简单的概念,其实可以理解为发送了一个信号。

    主要又这几个方法。

    1 Thread
    2 static boolean interrupted(); 
    3 void interrupt();
    4 boolean isInterrupted();

    其中Thread的实例方法interrupt是向这个实例线程发起中断信号的意思。

    实例方法isInterrupted和静态方法Interrupted都是用于检查有没有中断信号到来的意思。

    静态Interrupted几乎可以等价于Thread.currentThread().isInterrupted();但还是有一点点小差异。

    无论是静态的interrupted方法还是实例的isInterrupted方法最终都调用了一个本地的私有方法。

        /**
         * Tests if some Thread has been interrupted.  The interrupted state
         * is reset or not based on the value of ClearInterrupted that is
         * passed.
         */
        private native boolean isInterrupted(boolean ClearInterrupted);

    这个方法有一个boolean类型参数,指示如果有信号,在返回信号结果后是否清空信号。

    如果传递true,则isInterrupted返回当前信号情况,并把信号情况置为false。

    如果是false,则只获取当前信号的情况。

    接下来是一个实例。

    package Test;
    
    public class ThreadTest {
        public static void main(String[] args) throws InterruptedException {
            Thread.interrupted();
            MyThread thread = new MyThread();
            thread.start();
            Thread.sleep(1000);
            thread.interrupt(); //触发中断 发送中断信号
        }
    
        static class MyThread extends Thread {
            @Override
            public void run() {
                for (int i = 1; i <= 500000; i++) {
                    if (this.isInterrupted()) { //收到中断信号
                        System.out.println("end...");
                        break;
                    }
                    System.out.println(i);
                }
                super.run();
            }
        }
    }

    这个实例将在1s后停止1-500000的打印。结果如下:

    229876
    229877
    229878
    229879
    229880
    229881
    229882
    end...
    
    Process finished with exit code 0
  • 相关阅读:
    -bash: fork: Cannot allocate memory 问题的处理
    Docker top 命令
    docker常见问题修复方法
    The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
    What's the difference between encoding and charset?
    hexcode of é î Latin-1 Supplement
    炉石Advanced rulebook
    炉石bug反馈
    Sidecar pattern
    SQL JOIN
  • 原文地址:https://www.cnblogs.com/Gxqsd/p/14765403.html
Copyright © 2011-2022 走看看