Java:线程的三种中断方式

2023年2月22日08:29:39

前言

在 Java 中,并发机制非常重要,但并不是所有程序语言都支持线程。在以往的程序中,多以一个任务完成以后再进行下一个任务的模式进行,这样下一个任务的开始必须等待前一个任务的结束。Java 语言提供了并发机制,允许开发人员在程序中执行多个线程,每个线程完成一个功能,并与其他线程并发执行。这种机制被称为多线程。
而在多线程当中,有时我们不得不手动中止一个耗时的多线程,去将CPU的时间块分配给其他线程进行调度使用,本文着重讲解线程的两种中断方式,并针对其中一种提出优化的写法。

一、线程的Stop()操作

第一种方式是调用线程的stop方法,顾名思义就是直接让线程停止下来,这种方法是暴力的直接中断线程的运行

public class ThreadTest06 {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0;i<10;i++){
                    System.out.println(Thread.currentThread().getName()+"--->"+i);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        };
        thread.stop();
    }
}

可以看到在分支线程的run方法中,如果不给予线程干扰,该线程会在10秒内直接从0输出到9;但是在主线程当中,我们在让主线程沉睡5秒后,直接执行分支线程的stop()方法,从而中断分支线程的输出。

可参考输出结果如下:
Java:线程的三种中断方式
分支线程在输出5秒后直接被迫中止

二、线程的Interrupt()方法进行中断操作

1.stop()方法的缺点

stop()方法是可以直接让线程停止运行,但也同样存在致命的缺点,它的直接中断方式,并没有让线程留下存储数据的时间,这也极容易导致线程的数据丢失或不一致性的问题。以下介绍Interrupt()方法

2.Interrupt()方法

Interrupt方法来源是异常处理机制,在上方的Stop()方法中,我们可以看到在异常处理中,有这样一行代码:
catch (InterruptedException e)
当然Interrupt()方法也可针对于线程的睡眠和唤醒进行操作,但本文不做提及,以下是根据Interrupt进行改进后的线程中断方法:

代码如下(示例):

public class ThreadTest07 {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0;i<10;i++){
                    System.out.println(Thread.currentThread().getName()+"--->"+i);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        System.out.println(Thread.currentThread().getName()+"--->"+"中断");
                        e.printStackTrace();
                        return;

                    }
                }
            }
        });
        thread.start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        };
        thread.interrupt();
    }
}

输出结果如下:
Java:线程的三种中断方式

三、使用run标志位进行判断

除了以上提及的方法,还有最简单的方法便是在线程类当中添加标志位run,当标志位run为true时,线程继续执行,反之则进行中断处理。

public class ThreadTest08 {
    public static void main(String[] args) {
        MyRunnable4 myRunnable4 = new MyRunnable4();
        Thread thread = new Thread(myRunnable4);
        thread.start();

        //模拟五秒
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        myRunnable4.run=false;
    }
}
class MyRunnable4 implements Runnable{
    boolean run=true;
    @Override
    public void run() {
        for (int i=0;i<10;i++){
            if (run){
                System.out.println(Thread.currentThread().getName()+"--->"+i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            else {
                //终止当前线程,进行数据存储等操作
                return;
            }
        }
    }
}

此处是增添一个标志位的方法,当标志位为true时,继续执行操作;但当标志位为false时,则进行终止操作,进行数据的存储。

总结

以上介绍了线程的几种中断方式,希望对学习线程操作的小伙伴能够有所帮助。

  • 作者:Julian Qian
  • 原文链接:https://blog.csdn.net/qjyws/article/details/117323505
    更新时间:2023年2月22日08:29:39 ,共 2390 字。