0
点赞
收藏
分享

微信扫一扫

四、JUC-LockSupport与线程中断

一、线程中断机制

1、概述

  • 一个线程不应该由其他线程来强制中断或停止,而是应该由线程自己自行停止,所以,Thread.stop、Thread.suspend、Thread. resume都已经被废弃了
  • 在Java中没有办法立即停止一条线程,然而停止线程却显得尤为重要,如取消一个耗时操作。因此,Java提供了一种用于停止线程的协商机制 — 中断
  • 中断只是一种协商机制,Java没有给中断增加任何语法,中断的过程完全需要程序员自己实现
  • 若要中断一个线程,你需要手动调用该线程的interrupt方法,该方法也仅仅是将线程对象的中断标识设为true
  • 每个线程对象中都有一个标识,用于标识线程是否被中断;该标识位为true表示中断,为false表示未中断;通过调用线程对象的interru pt方法将线程的标识位设为true;可以在别的线程中调用,也可以在自己的线程中调用

2、API介绍

70.png 71.png

1、interrupt

源码

    public void interrupt() {
        if (this != Thread.currentThread())
            checkAccess();

        synchronized (blockerLock) {
            Interruptible b = blocker;
            if (b != null) {
                interrupt0();           // 底层调用了native方法
                b.interrupt(this);
                return;
            }
        }
        interrupt0();
    }

实例方法,interrupt()仅仅是设置线程的中断状态为true,发起一个协商,而不会立刻停止线程。 当一个线程调用interrupt()时: 1、如果线程处于正常活动状态,那么会将该线程的中断标志设置为ture,仅此而已,被设置中断标志的线程将继续正常运行,不受影响。所以,interrupt()并不能真正中断线程,需要被调用的线程自己配合才行。 2、如果线程处于被阻塞状态(sleep,wait,join等),在别的线程中调用当前线程对象的interrupt方法,那么线程将立即退出被阻塞状态,并抛出一个InterruptedException异常。

2、interrupted

源码

    public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }

静态方法,判断线程是否被中断,并清除当前中断状态。这个方法做了两件事 1、返回当前线程的中断状态,测试当前线程是否已经被中断 2、将当前线程的中断状态清除,并重新设置为false,取消线程的中断状态

3、isInterrupted

源码

    public boolean isInterrupted() {
//false:不需要清除中断状态
        return isInterrupted(false);
    }


 private native boolean isInterrupted(boolean ClearInterrupted);

实例方法,判断当前线程是否被中断

3、终端机制的疑问

1、如何停止中断运行中的线程

1、通过一个volatile变量实现

package com.lori.juc2023.juc4;

import java.util.concurrent.TimeUnit;

public class InterruptDemo {
    static volatile boolean isStop = false;
    public static void main(String[] args) {

        new Thread(()->{
                    while (true){
                        if(isStop){
                            System.out.println("*************isStop被修改为true,程序停止");
                            break;
                        }
                        System.out.println(Thread.currentThread().getName()+":运行中*******************");
                    }
                },"t1").start();

         try {
             TimeUnit.MILLISECONDS.sleep(5);} catch (InterruptedException e) {throw new RuntimeException(e);}
           new Thread(()->{
                       isStop=true;
               System.out.println(Thread.currentThread().getName()+"运行*******************");
                   },"t2").start();
    }
}

72.png

2、通过AtomicBoolean

package com.lori.juc2023.juc4;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class InterruptDemo1 {
    static AtomicBoolean atomicBoolean = new AtomicBoolean(false);
    public static void main(String[] args) {
        new Thread(()->{
            while (true){
                if(atomicBoolean.get()){
                    System.out.println("*************atomicBoolean被修改为true,程序停止");
                    break;
                }
                System.out.println(Thread.currentThread().getName()+":运行中*******************");
            }
        },"t1").start();

        try {
            TimeUnit.MILLISECONDS.sleep(5);} catch (InterruptedException e) {throw new RuntimeException(e);}
        new Thread(()->{
            atomicBoolean.set(true);
            System.out.println(Thread.currentThread().getName()+"运行*******************");
        },"t2").start();

    }
}

73.png

3、通过Thread类自带的中断API实例方法实现

在需要中断的线程中不断监听中断状态,一旦发生中断,就执行相应的中断处理业务逻辑stop线程

package com.lori.juc2023.juc4;

import java.util.concurrent.TimeUnit;

public class InterruptDemo2 {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
          while (true){
              if(Thread.currentThread().isInterrupted()){
                  System.out.println("*************Interrupt被修改为true,程序停止");
                  break;
              }
              System.out.println(Thread.currentThread().getName()+"*******在执行");
          }
        },"t1");
        t1.start();

        try {
            TimeUnit.MILLISECONDS.sleep(5);} catch (InterruptedException e) {throw new RuntimeException(e);}
        new Thread(()->{
           t1.interrupt();
            System.out.println(Thread.currentThread().getName()+"运行*******************");
        },"t2").start();

    }
}

75.png

2、当前线程的终端标识为true,是不是线程就立刻停止

当前线程的终端标识为true,线程不会立即中断

package com.lori.juc2023.juc4;

import java.util.concurrent.TimeUnit;

public class InterruptDemo3 {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 300; i++) {
                System.out.println("******************"+i);
            }
            System.out.println("t1线程调用Interrupt方法后的中断标识(02):"+Thread.currentThread().isInterrupted());
        }, "t1");
        t1.start();
        System.out.println("t1线程的默认标识"+t1.isInterrupted());
         try {TimeUnit.MILLISECONDS.sleep(2);} catch (InterruptedException e) {throw new RuntimeException(e);}
         t1.interrupt();
        System.out.println("t1线程调用Interrupt方法后的中断标识(01):"+t1.isInterrupted());

    }
}

76.png

package com.lori.juc2023.juc4;

import java.util.concurrent.TimeUnit;

public class InterruptDemo3 {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 300; i++) {
                System.out.println("******************"+i);
            }
            System.out.println("t1线程调用Interrupt方法后的中断标识(02):"+Thread.currentThread().isInterrupted());
        }, "t1");
        t1.start();
        System.out.println("t1线程的默认标识"+t1.isInterrupted());
         try {TimeUnit.MILLISECONDS.sleep(2);} catch (InterruptedException e) {throw new RuntimeException(e);}
         t1.interrupt();
        System.out.println("t1线程调用Interrupt方法后的中断标识(01):"+t1.isInterrupted());
        //线程停止后,停止状态又会被变为false
        try {TimeUnit.MILLISECONDS.sleep(2000);} catch (InterruptedException e) {throw new RuntimeException(e);}
        System.out.println("t1线程调用Interrupt方法后的中断标识(03):"+t1.isInterrupted());
    }
}

77.png

package com.lori.juc2023.juc4;

import java.util.concurrent.TimeUnit;

public class InterruptDemo3 {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
           while (true){
                if (Thread.currentThread().isInterrupted()){
                    System.out.println(Thread.currentThread().getName()+"\t"+"中断标识位:"+Thread.currentThread().isInterrupted()+"程序停止");
                    break;
                }
                //睡一会
               try {
                   Thread.sleep(200);
               } catch (InterruptedException e) {
                   //没有它,此线程不会停止
                   Thread.currentThread().interrupt();
                   throw new RuntimeException(e);
               }
               System.out.println("hello********");
           }
        }, "t1");
        t1.start();
         try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {throw new RuntimeException(e);}

           new Thread(()->{
               t1.interrupt();
                   },"t2").start();

    }
}

78.png

sleep方法抛出InterruptedException异常后,中断标识被置为false,我们在catch没有调用Thread.currentThread().interrupt();将标志设置为true,就导致了无限死循环。

3、静态方法Thread.interrupted(),怎么理解

package com.lori.juc2023.juc4;

public class InterruptDemo6 {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().isInterrupted());//false
        System.out.println(Thread.interrupted());//false
        System.out.println(Thread.currentThread().isInterrupted());//false
        Thread.currentThread().interrupt();
        System.out.println(Thread.interrupted());//true
        System.out.println(Thread.currentThread().isInterrupted());//false

    }
}
举报

相关推荐

0 条评论