zoukankan      html  css  js  c++  java
  • java多线程-中断线程

    大纲:

    1. java线程的中断原则
    2. 中断相关方法
    3. 中断实例

    一、java线程中断原则

    java中断是一种协作机制,每一个线程的中断都由线程自己处理,其他线程只是给要中断的线程一个中断标志。

    二、相关方法

    1.把线程对象的中断标志置为true

    public void interrupt()

    2.判断线程对象的中断标志

    public boolean isInterrupted()

    3.判断当前的线程中断标志,并清除该标志(注意这个是static方法,上面2个方法由线程对象调用)

    public static boolean interrupted()

    三、中断实例

     中断只分2种情况,一种线程正常运行,一种线程阻塞情况。

    3.1正常运行:

    public static void main(String[] args) throws InterruptedException {
            Thread thread1 = new Thread(() -> {
                for (int i = 0; i < 5000; i++) {
                    if(Thread.currentThread().isInterrupted()){
                        System.out.println("break");
                        break;
                    }
                    System.out.println(i);
                }
            });
            thread1.start();
            Thread.sleep(5);
            thread1.interrupt();
        }

    thread1线程正常工作时候,主线程把它的中断置为true,但并不会抛出InterruptedException异常,只有thread1线程内不断去判断当前线程状态,直到发现标志位变了,自己处理后续逻辑。

    这里判断的依据是Thread.currentThread().isInterrupted(),根据上面的解释是获取线程的中断标志。当中断标志为true的时候,执行中断操作。

    现在由一个场景:需要中断2次才能执行中断操作,上面这种判断就不行了

    public static void main(String[] args) throws InterruptedException {
            Thread thread = new Thread(() -> {
                int index = 0;
                for (int i = 0; i < 5000; i++) {
                    if(Thread.interrupted()){
                        if(index==1){
                            System.out.println("break");
                            break;
                        }
                        index++;
                    }
                    System.out.println(i);
                }
            });
            thread.start();
            thread.interrupt();
            Thread.sleep(10);
            thread.interrupt();
        }

    以上代码可以通过Thread.interrupted判断线程中断标志,当中断标志是true时候,interrupted方法还能清除中断标志,这样就可以统计到第二次中断。

    3.2阻塞状态

    线程阻塞在lockInterruptibly()、sleep()、wait()等会抛出InterruptedException的方法时,我们调用该线程的interrupt方法,线程会抛出InterruptedException异常。

    public static void main(String[] args) throws InterruptedException {
            Thread thread = new Thread(() -> {
                try {
                    for (int i = 0; i < 5000; i++) {
                        System.out.println(i);
                    }
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            thread.start();
            thread.interrupt();
        }

    线程打印4999后阻塞,由于线程的中断标志已经被置为true,则立即抛出InterruptedException。

  • 相关阅读:
    微服务架构总结
    微服务-网关服务
    HttpClient-RestTemplate-Feign
    RPC和REST
    Springmvc的拦截器执行顺序及各方法作用
    秒杀系统优化方案(下)吐血整理
    秒杀系统优化方案(上)吐血整理
    分布式session的管理
    缓存设计——缓存和数据库的数据一致性
    个人理解的javascript作用域链与闭包
  • 原文地址:https://www.cnblogs.com/liuboyuan/p/12556118.html
Copyright © 2011-2022 走看看