Young's blog Young's blog
首页
Spring
  • 前端文章1

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《JavaScript高级程序设计》
    • 《ES6 教程》
    • 《Vue》
    • 《React》
    • 《TypeScript 从零实现 axios》
    • 《Git》
    • TypeScript
    • JS设计模式总结
  • HTML
  • CSS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

Young

首页
Spring
  • 前端文章1

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《JavaScript高级程序设计》
    • 《ES6 教程》
    • 《Vue》
    • 《React》
    • 《TypeScript 从零实现 axios》
    • 《Git》
    • TypeScript
    • JS设计模式总结
  • HTML
  • CSS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • 关于 JVM JDK 和 JRE 最详细通俗的解答
  • Java基础之讲透面向对象三大特征
  • 文件读写操作与常用技巧分享
  • 高效快捷读写文件之 RandomAccessFile 类解说
  • java的内存模型
  • 面试官:如何停止一个正在运行的线程?
    • 1. 停止不了的线程
    • 2. 判断线程是否停止状态
    • 3. 能停止的线程 -- 异常法
    • 4. 在沉睡中停止
    • 5. 能停止的线程 --- 暴力停止
    • 6. 方法 stop() 与 java.lang.ThreadDeath 异常
    • 7. 释放锁的不良后果
    • 8. 使用 return 停止线程
  • 集合

  • linux卸载自带java JDK,安装配置java jdk环境
  • java 实现LRU 算法
  • Java
andanyang
2022-07-13
目录

面试官:如何停止一个正在运行的线程?

# 前言

停止一个线程意味着在任务处理完任务之前停掉正在做的操作,也就是放弃当前的操作。停止一个线程可以用 Thread.stop() 方法,但最好不要用它。虽然它确实可以停止一个正在运行的线程,但是这个方法是不安全的,而且是已被废弃的方法。在 java 中有以下 3 种方法可以终止正在运行的线程:

  1. 使用退出标志,使线程正常退出,也就是当 run 方法完成后线程终止。

  2. 使用 stop 方法强行终止,但是不推荐这个方法,因为 stop 和 suspend 及 resume 一样都是过期作废的方法。

  3. 使用 interrupt 方法中断线程。

# 1. 停止不了的线程

interrupt() 方法的使用效果并不像 for+break 语句那样,马上就停止循环。调用 interrupt 方法是在当前线程中打了一个停止标志,并不是真的停止线程。

public class MyThread extends Thread {
    public void run(){
        super.run();
        for(int i=0; i<500000; i++){
            System.out.println("i="+(i+1));
        }
    }
}

public class Run {
    public static void main(String args[]){
        Thread thread = new MyThread();
        thread.start();
        try {
            Thread.sleep(2000);
            thread.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

输出结果:

...
i=499994
i=499995
i=499996
i=499997
i=499998
i=499999
i=500000


1
2
3
4
5
6
7
8
9
10

# 2. 判断线程是否停止状态

Thread.java 类中提供了两种方法:

  1. this.interrupted(): 测试当前线程是否已经中断;

  2. this.isInterrupted(): 测试线程是否已经中断;

那么这两个方法有什么图区别呢?

我们先来看看 this.interrupted() 方法的解释:测试当前线程是否已经中断,当前线程是指运行 this.interrupted() 方法的线程。

public class MyThread extends Thread {
    public void run(){
        super.run();
        for(int i=0; i<500000; i++){
            i++;
//            System.out.println("i="+(i+1));
        }
    }
}

public class Run {
    public static void main(String args[]){
        Thread thread = new MyThread();
        thread.start();
        try {
            Thread.sleep(2000);
            thread.interrupt();

            System.out.println("stop 1??" + thread.interrupted());
            System.out.println("stop 2??" + thread.interrupted());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

运行结果:

stop 1??false
stop 2??false


1
2
3
4

类 Run.java 中虽然是在 thread 对象上调用以下代码:thread.interrupt(), 后面又使用

System.out.println("stop 1??" + thread.interrupted());
System.out.println("stop 2??" + thread.interrupted());


1
2
3
4

来判断 thread 对象所代表的线程是否停止,但从控制台打印的结果来看,线程并未停止,这也证明了 interrupted() 方法的解释,测试当前线程是否已经中断。这个当前线程是 main,它从未中断过,所以打印的结果是两个 false.

如何使 main 线程产生中断效果呢?

public class Run2 {
    public static void main(String args[]){
        Thread.currentThread().interrupt();
        System.out.println("stop 1??" + Thread.interrupted());
        System.out.println("stop 2??" + Thread.interrupted());

        System.out.println("End");
    }
}


1
2
3
4
5
6
7
8
9
10
11

运行效果为:

stop 1??true
stop 2??false
End


1
2
3
4
5

方法 interrupted() 的确判断出当前线程是否是停止状态。但为什么第 2 个布尔值是 false 呢?官方帮助文档中对 interrupted 方法的解释:测试当前线程是否已经中断。线程的中断状态由该方法清除。 换句话说,如果连续两次调用该方法,则第二次调用返回 false。

下面来看一下 inInterrupted() 方法。

public class Run3 {
    public static void main(String args[]){
        Thread thread = new MyThread();
        thread.start();
        thread.interrupt();
        System.out.println("stop 1??" + thread.isInterrupted());
        System.out.println("stop 2??" + thread.isInterrupted());
    }
}


1
2
3
4
5
6
7
8
9
10
11

运行结果:

stop 1??true
stop 2??true


1
2
3
4

isInterrupted() 并为清除状态,所以打印了两个 true。

# 3. 能停止的线程 -- 异常法

有了前面学习过的知识点,就可以在线程中用 for 语句来判断一下线程是否是停止状态,如果是停止状态,则后面的代码不再运行即可:

public class MyThread extends Thread {
    public void run(){
        super.run();
        for(int i=0; i<500000; i++){
            if(this.interrupted()) {
                System.out.println("线程已经终止, for循环不再执行");
                break;
            }
            System.out.println("i="+(i+1));
        }
    }
}

public class Run {
    public static void main(String args[]){
        Thread thread = new MyThread();
        thread.start();
        try {
            Thread.sleep(2000);
            thread.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

运行结果:

...
i=202053
i=202054
i=202055
i=202056
线程已经终止, for循环不再执行


1
2
3
4
5
6
7
8

上面的示例虽然停止了线程,但如果 for 语句下面还有语句,还是会继续运行的。看下面的例子:

public class MyThread extends Thread {
    public void run(){
        super.run();
        for(int i=0; i<500000; i++){
            if(this.interrupted()) {
                System.out.println("线程已经终止, for循环不再执行");
                break;
            }
            System.out.println("i="+(i+1));
        }

        System.out.println("这是for循环外面的语句,也会被执行");
    }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

使用 Run.java 执行的结果是:

...
i=180136
i=180137
i=180138
i=180139
线程已经终止, for循环不再执行
这是for循环外面的语句,也会被执行


1
2
3
4
5
6
7
8
9

如何解决语句继续运行的问题呢?看一下更新后的代码:

public class MyThread extends Thread {
    public void run(){
        super.run();
        try {
            for(int i=0; i<500000; i++){
                if(this.interrupted()) {
                    System.out.println("线程已经终止, for循环不再执行");
                        throw new InterruptedException();
                }
                System.out.println("i="+(i+1));
            }

            System.out.println("这是for循环外面的语句,也会被执行");
        } catch (InterruptedException e) {
            System.out.println("进入MyThread.java类中的catch了。。。");
            e.printStackTrace();
        }
    }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

使用 Run.java 运行的结果如下:

...
i=203798
i=203799
i=203800
线程已经终止, for循环不再执行
进入MyThread.java类中的catch了。。。
java.lang.InterruptedException
 at thread.MyThread.run(MyThread.java:13)

1
2
3
4
5
6
7
8
9

# 4. 在沉睡中停止

如果线程在 sleep() 状态下停止线程,会是什么效果呢?

public class MyThread extends Thread {
    public void run(){
        super.run();

        try {
            System.out.println("线程开始。。。");
            Thread.sleep(200000);
            System.out.println("线程结束。");
        } catch (InterruptedException e) {
            System.out.println("在沉睡中被停止, 进入catch, 调用isInterrupted()方法的结果是:" + this.isInterrupted());
            e.printStackTrace();
        }

    }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

使用 Run.java 运行的结果是:

线程开始。。。
在沉睡中被停止, 进入catch, 调用isInterrupted()方法的结果是:false
java.lang.InterruptedException: sleep interrupted
 at java.lang.Thread.sleep(Native Method)
 at thread.MyThread.run(MyThread.java:12)


1
2
3
4
5
6
7

从打印的结果来看, 如果在 sleep 状态下停止某一线程,会进入 catch 语句,并且清除停止状态值,使之变为 false。

前一个实验是先 sleep 然后再用 interrupt() 停止,与之相反的操作在学习过程中也要注意:

public class MyThread extends Thread {
    public void run(){
        super.run();
        try {
            System.out.println("线程开始。。。");
            for(int i=0; i<10000; i++){
                System.out.println("i=" + i);
            }
            Thread.sleep(200000);
            System.out.println("线程结束。");
        } catch (InterruptedException e) {
             System.out.println("先停止,再遇到sleep,进入catch异常");
            e.printStackTrace();
        }

    }
}

public class Run {
    public static void main(String args[]){
        Thread thread = new MyThread();
        thread.start();
        thread.interrupt();
    }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

运行结果:

i=9998
i=9999
先停止,再遇到sleep,进入catch异常
java.lang.InterruptedException: sleep interrupted
 at java.lang.Thread.sleep(Native Method)
 at thread.MyThread.run(MyThread.java:15)


1
2
3
4
5
6
7
8

# 5. 能停止的线程 --- 暴力停止

使用 stop() 方法停止线程则是非常暴力的。

public class MyThread extends Thread {
    private int i = 0;
    public void run(){
        super.run();
        try {
            while (true){
                System.out.println("i=" + i);
                i++;
                Thread.sleep(200);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class Run {
    public static void main(String args[]) throws InterruptedException {
        Thread thread = new MyThread();
        thread.start();
        Thread.sleep(2000);
        thread.stop();
    }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

运行结果:

i=0
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9

Process finished with exit code 0
1
2
3
4
5
6
7
8
9
10
11
12

# 6. 方法 stop() 与 java.lang.ThreadDeath 异常

调用 stop() 方法时会抛出 java.lang.ThreadDeath 异常,但是通常情况下,此异常不需要显示地捕捉。

public class MyThread extends Thread {
    private int i = 0;
    public void run(){
        super.run();
        try {
            this.stop();
        } catch (ThreadDeath e) {
            System.out.println("进入异常catch");
            e.printStackTrace();
        }
    }
}

public class Run {
    public static void main(String args[]) throws InterruptedException {
        Thread thread = new MyThread();
        thread.start();
    }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

stop() 方法以及作废,因为如果强制让线程停止有可能使一些清理性的工作得不到完成。另外一个情况就是对锁定的对象进行了解锁,导致数据得不到同步的处理,出现数据不一致的问题。

# 7. 释放锁的不良后果

使用 stop() 释放锁将会给数据造成不一致性的结果。如果出现这样的情况,程序处理的数据就有可能遭到破坏,最终导致程序执行的流程错误,一定要特别注意:

public class SynchronizedObject {
    private String name = "a";
    private String password = "aa";

    public synchronized void printString(String name, String password){
        try {
            this.name = name;
            Thread.sleep(100000);
            this.password = password;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

public class MyThread extends Thread {
    private SynchronizedObject synchronizedObject;
    public MyThread(SynchronizedObject synchronizedObject){
        this.synchronizedObject = synchronizedObject;
    }

    public void run(){
        synchronizedObject.printString("b", "bb");
    }
}

public class Run {
    public static void main(String args[]) throws InterruptedException {
        SynchronizedObject synchronizedObject = new SynchronizedObject();
        Thread thread = new MyThread(synchronizedObject);
        thread.start();
        Thread.sleep(500);
        thread.stop();
        System.out.println(synchronizedObject.getName() + "  " + synchronizedObject.getPassword());
    }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

输出结果:

b  aa


1
2
3

由于 stop()方法以及在 JDK 中被标明为 “过期 / 作废” 的方法,显然它在功能上具有缺陷,所以不建议在程序张使用 stop()方法。

# 8. 使用 return 停止线程

将方法 interrupt() 与 return 结合使用也能实现停止线程的效果:

public class MyThread extends Thread {
    public void run(){
        while (true){
            if(this.isInterrupted()){
                System.out.println("线程被停止了!");
                return;
            }
            System.out.println("Time: " + System.currentTimeMillis());
        }
    }
}

public class Run {
    public static void main(String args[]) throws InterruptedException {
        Thread thread = new MyThread();
        thread.start();
        Thread.sleep(2000);
        thread.interrupt();
    }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

输出结果:

...
Time: 1467072288503
Time: 1467072288503
Time: 1467072288503
线程被停止了!
1
2
3
4
5

不过还是建议使用 “抛异常” 的方法来实现线程的停止,因为在 catch 块中还可以将异常向上抛,使线程停止事件得以传播。

编辑 (opens new window)
上次更新: 2024/04/19, 08:52:45
java的内存模型
多线程环境下,HashMap为什么会出现死循环

← java的内存模型 多线程环境下,HashMap为什么会出现死循环→

最近更新
01
idea 热部署插件 JRebel 安装及破解,不生效问题解决
04-10
02
spark中代码的执行位置(Driver or Executer)
12-12
03
大数据技术之 SparkStreaming
12-12
更多文章>
Theme by Vdoing | Copyright © 2019-2024 Young | MIT License
浙ICP备20002744号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式