线程的中断操作案例详解

为什么需要中断操作?

案例:写一个线程死循环,比如运行到某一个时刻,我需要去关掉

public class Demo implements Runnable {

    @Override
    public void run() {
        while (true){
            System.out.println(Thread.currentThread().getName());
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String [] args){

        Thread thread = new Thread(new Demo());
        thread.start();
    }
}

方式一:stop()

古老jdk提供了stop()废弃方法, 开发中不要使用。因为一调用,线程就立刻停止,此时有可能引发相应的线程安全性问题
在这里插入图片描述

案例:执行run方法 i++ 休眠两秒 主线程休眠1秒 调stop方法 立刻就暴力停掉了,后面的代码还没执行就停了。

public class UnsafeWithStop extends Thread {

    private int i = 0;
    private int j = 0;

    @Override
    public void run() {
        i++;
        try {
            Thread.sleep(2000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        j++;
    }
    public void printf(){
        System.out.println("i的值:"+i);
        System.out.println("j的值:"+j);
    }

    public static void main(String [] args) throws InterruptedException {
        UnsafeWithStop unsafeWithStop = new UnsafeWithStop();
        unsafeWithStop.start();
        Thread.sleep(1000L);
        unsafeWithStop.stop();
        unsafeWithStop.printf();
    }
}

方式二:Thread.interrupt方法

在这里插入图片描述

案例:调用interrupt不中断

public class InterrupDemo implements Runnable {
    @Override
    public void run() {
        while (true){
            System.out.println(Thread.currentThread().getName());
        }
    }

    public static void main(String [] args) throws InterruptedException {
        Thread thread = new Thread(new InterrupDemo());
        thread.start();
        Thread.sleep(1000L);
        thread.interrupt();
    }
}

源码中有写出,大致意思是调用interrupt方法,会给这个线程一个标记,标记这个线程准备结束运行,如果你在执行也不会结束

条件判断是否被标记

public class InterrupDemo implements Runnable {
    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()){//判断是否终止运行
            System.out.println(Thread.currentThread().getName());
        }
    }

    public static void main(String [] args) throws InterruptedException {
        Thread thread = new Thread(new InterrupDemo());
        thread.start();
        Thread.sleep(1000L);
        thread.interrupt();
    }
}

方式三:自定义标识终止线程

案例

只是定义一个volatile标识判断

public class MyInterrupDemo implements Runnable{

    //线程终止与否标志
    private static volatile boolean FLAG = true;

    @Override
    public void run() {
        while (FLAG){
            System.out.println(Thread.currentThread().getName());
        }
    }

    public static void main(String [] args) throws InterruptedException {
        Thread thread = new Thread(new MyInterrupDemo());
        thread.start();
        Thread.sleep(1000L);
        FLAG = false;
    }
}

猜你喜欢

转载自blog.csdn.net/q736317048/article/details/113797994