多线程——停止线程

停止线程是多线程中的一个技术点,在Thread类的方法中,与停止线程有关的有: interrupt(),interrupted()和isInterrupted()
还有一个stop()方法,该方法因”unsafe”而被标记为”Deprecated”,
本博客是关于停止线程的探讨,不会涉及到被弃用的方法,作为自我学习总结。

1. 判断线程是否是停止状态

可以参考: 多线程——interrupt(),interrupted()和isInterrupted()

2. 停止线程的方法

Java中在不使用“被弃用的”方法的情况下,停止线程主要由一下两种方式:

  • 使用退出标识,使线程正常退出,也就是当run()方法完成后线程终止;
  • 使用interupt()方法中断线程。

下面是停止线程的具体的方法。

1. 在for循环中判断线程是否停止

在for循环中判断一下当前正在执行的线程是否是停止状态,如果是,则用break退出循环。

代码实例:

/*
 * 停止线程:在for循环中判断线程是否停止
 */
public class Test_stopThread1 implements Runnable {

    @Override
    public void run() {
        for(int i=0; i<500000; i++){
            if(Thread.currentThread().isInterrupted()){
                System.out.println("当前线程:"+Thread.currentThread().getName());
                System.out.println("线程中断, 退出for循环");
                break;
            }
            System.out.println("i=: "+i);
        }
        System.out.println("已经退出for循环了,如果我被打印了,说明存在语句继续运行的问题=.=");
    }

    public static void main(String[] args) {            
        try {
            Test_stopThread1 r = new Test_stopThread1();
            Thread t = new Thread(r,"test");
            t.start();
            Thread.sleep(1000);
            t.interrupt();    //中断线程t

            System.out.println("是否停止?: "+t.isInterrupted());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

运行结果:

这里写图片描述

分析:
可以看到,当i=94716时打印停止,for语句退出,50万条数据没有打印完,
但是,for语句后面的语句仍然被执行了,如何解决语句继续运行的问题呢?可以使用下面的这种方法。

2. 在for循环中判断线程是否停止,强行抛出异常

与上面类似,都需要在for循环中判断一当前正在执行的线程是否是停止状态,如果是,则用强行抛出InterruptedException异常,
这样做就不会有语句继续运行的问题了。

代码实例:

/*
 * 停止线程:在for循环中判断线程是否停止,强制抛出异常
 */
public class Test_stopThread2 implements Runnable {

    @Override
    public void run() {
        try {
            for(int i=0; i<500000; i++){
                if(Thread.currentThread().isInterrupted()){
                    System.out.println("当前线程:"+Thread.currentThread().getName());
                    System.out.println("线程中断, 退出for循环");
                    throw new InterruptedException();  //强行抛出异常
                }
                System.out.println("i=: "+i);
            }
            System.out.println("已经退出for循环了,如果我被打印了,说明存在语句继续运行的问题=.=");
        } catch (InterruptedException e) {
            System.out.println("进入到了run()方法的catch了~");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        try {
            Test_stopThread2 r = new Test_stopThread2();
            Thread t = new Thread(r,"test");
            t.start();
            Thread.sleep(1000);
            t.interrupt();    //中断线程t

            System.out.println("是否停止?: "+t.isInterrupted());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

运行结果:

这里写图片描述

分析:
可以看到,当i=93800时打印停止,for语句退出,50万条数据没有打印完,抛出InterruptedException异常,也没有语句继续执行的问题了~

参考书籍:《Java多线程编程核心技术》,感谢作者~

献上昨夜的月食美照~

这里写图片描述

猜你喜欢

转载自blog.csdn.net/gxx_csdn/article/details/79228904