004 线程的interrupt方法

一. 概述

  当一个线程启动之后,我们如何终结一个线程呢?

  在Thread之中原先的stop()等方法都被废除掉了,那现在我们可以利用的就是线程中断的概念.

  我们需要理解的就是,线程中断实际上是我们控制线程终结的一个方式.


二 .线程终结的方法

 线程的实例方法,我们获取线程的实例引用之后,可以调用该方法,name线程就会获得一个中断信号.  

 public void interrupt()public static boolean interrupted()

线程的静态方法,用于判断线程是否哦被打断,当该方法被调用之后,线程的打断状态会被清除.

public static boolean interrupted()

用于判断线程时候被打断

public boolean isInterrupted()

三 . 如何使用中断终结一个线程 

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(()->{
            for(;;) {
                if(!Thread.currentThread().isInterrupted()) {
                    System.out.println("thread is running ....");
                }else {
                    return ;
                }
            } 
        });
        
        t.start();
        
        Thread.sleep(3000);
        t.interrupt();
    }

在上面的实例之中,我们使用API判断线程是否处于被打断的状态中,当线程被打断之后,我们直接就中断线程的运行.

看下面的例子:我们了解一下InterruptedException 的作用:

    public static void main(String[] args) throws Exception {
        Thread t = new Thread(()->{
            for(;;) {
                try {
                    System.out.println("子线程开始睡眠...");
                    TimeUnit.SECONDS.sleep(1000000);
                } catch (InterruptedException e) {
                    System.out.println("子线程被打断..");
                    return ;
                }
            } 
        });
        
        t.start();
        
        Thread.sleep(3000);
        t.interrupt();
    }

从上面的例子之中,我们可以看到我们通过捕获线程的被打断的异常就能实现线程的终结

原文地址:https://www.cnblogs.com/trekxu/p/8975123.html