欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java終止正在運行的線程的三種方法

 更新時間:2025年03月21日 10:30:20   作者:城南vision  
停止一個線程意味著在任務(wù)處理完任務(wù)之前停掉正在做的操作,也就是放棄當前的操作,停止一個線程可以用Thread.stop()方法,但最好不要用它,本文給大家介紹了Java終止正在運行的線程的三種方法,需要的朋友可以參考下

前言

停止一個線程意味著在任務(wù)處理完任務(wù)之前停掉正在做的操作,也就是放棄當前的操作。停止一個線程可以用Thread.stop()方法,但最好不要用它。雖然它確實可以停止一個正在運行的線程,但是這個方法是不安全的,而且是已被廢棄的方法。在java中有以下3種方法可以終止正在運行的線程:

  1. 使用退出標志,使線程正常退出,也就是當run方法完成后線程終止。
  2. 使用stop方法強行終止,但是不推薦這個方法,因為stop和suspend及resume一樣都是過期作廢的方法。
  3. 使用interrupt方法中斷線程。

1. 停止不了的線程

interrupt()方法的使用效果并不像for+break語句那樣,馬上就停止循環(huán)。調(diào)用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();
        }
    }
}

輸出結(jié)果:

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

2. 判斷線程是否停止狀態(tài)

Thread.java類中提供了兩種方法:

  1. this.interrupted(): 測試當前線程是否已經(jīng)中斷;
  2. this.isInterrupted(): 測試線程是否已經(jīng)中斷;

那么這兩個方法有什么圖區(qū)別呢?

我們先來看看this.interrupted()方法的解釋:測試當前線程是否已經(jīng)中斷,當前線程是指運行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();
        }
    }
}

運行結(jié)果:

stop 1??false
stop 2??false

類Run.java中雖然是在thread對象上調(diào)用以下代碼:thread.interrupt(), 后面又使用

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

來判斷thread對象所代表的線程是否停止,但從控制臺打印的結(jié)果來看,線程并未停止,這也證明了interrupted()方法的解釋,測試當前線程是否已經(jīng)中斷。這個當前線程是main,它從未中斷過,所以打印的結(jié)果是兩個false.

如何使main線程產(chǎn)生中斷效果呢?

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");
    }
}

運行效果為:

stop 1??true
stop 2??false
End

方法interrupted()的確判斷出當前線程是否是停止狀態(tài)。但為什么第2個布爾值是false呢?官方幫助文檔中對interrupted方法的解釋:測試當前線程是否已經(jīng)中斷。線程的中斷狀態(tài)由該方法清除。 換句話說,如果連續(xù)兩次調(diào)用該方法,則第二次調(diào)用返回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());
    }
}

運行結(jié)果:

stop 1??true
stop 2??true

isInterrupted()并為清除狀態(tài),所以打印了兩個true。

3. 能停止的線程–異常法

有了前面學習過的知識點,就可以在線程中用for語句來判斷一下線程是否是停止狀態(tài),如果是停止狀態(tài),則后面的代碼不再運行即可:

public class MyThread extends Thread {
    public void run(){
        super.run();
        for(int i=0; i<500000; i++){
            if(this.interrupted()) {
                System.out.println("線程已經(jīng)終止, for循環(huán)不再執(zhí)行");
                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();
        }
    }
}

運行結(jié)果:

...
i=202053
i=202054
i=202055
i=202056
線程已經(jīng)終止, for循環(huán)不再執(zhí)行

上面的示例雖然停止了線程,但如果for語句下面還有語句,還是會繼續(xù)運行的??聪旅娴睦樱?/p>

public class MyThread extends Thread {
    public void run(){
        super.run();
        for(int i=0; i<500000; i++){
            if(this.interrupted()) {
                System.out.println("線程已經(jīng)終止, for循環(huán)不再執(zhí)行");
                break;
            }
            System.out.println("i="+(i+1));
        }

        System.out.println("這是for循環(huán)外面的語句,也會被執(zhí)行");
    }
}

使用Run.java執(zhí)行的結(jié)果是:

...
i=180136
i=180137
i=180138
i=180139
線程已經(jīng)終止, for循環(huán)不再執(zhí)行
這是for循環(huán)外面的語句,也會被執(zhí)行

如何解決語句繼續(xù)運行的問題呢?看一下更新后的代碼:

public class MyThread extends Thread {
    public void run(){
        super.run();
        try {
            for(int i=0; i<500000; i++){
                if(this.interrupted()) {
                    System.out.println("線程已經(jīng)終止, for循環(huán)不再執(zhí)行");
                        throw new InterruptedException();
                }
                System.out.println("i="+(i+1));
            }

            System.out.println("這是for循環(huán)外面的語句,也會被執(zhí)行");
        } catch (InterruptedException e) {
            System.out.println("進入MyThread.java類中的catch了。。。");
            e.printStackTrace();
        }
    }
}

使用Run.java運行的結(jié)果如下:

...
i=203798
i=203799
i=203800
線程已經(jīng)終止, for循環(huán)不再執(zhí)行
進入MyThread.java類中的catch了。。。
java.lang.InterruptedException
 at thread.MyThread.run(MyThread.java:13)

4. 在沉睡中停止

如果線程在sleep()狀態(tài)下停止線程,會是什么效果呢?

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

        try {
            System.out.println("線程開始。。。");
            Thread.sleep(200000);
            System.out.println("線程結(jié)束。");
        } catch (InterruptedException e) {
            System.out.println("在沉睡中被停止, 進入catch, 調(diào)用isInterrupted()方法的結(jié)果是:" + this.isInterrupted());
            e.printStackTrace();
        }

    }
}

使用Run.java運行的結(jié)果是:

線程開始。。。
在沉睡中被停止, 進入catch, 調(diào)用isInterrupted()方法的結(jié)果是:false
java.lang.InterruptedException: sleep interrupted
 at java.lang.Thread.sleep(Native Method)
 at thread.MyThread.run(MyThread.java:12)

從打印的結(jié)果來看, 如果在sleep狀態(tài)下停止某一線程,會進入catch語句,并且清除停止狀態(tài)值,使之變?yōu)閒alse。

前一個實驗是先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("線程結(jié)束。");
        } 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();
    }
}

運行結(jié)果:

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)

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();
    }
}

運行結(jié)果:

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

6.方法stop()與java.lang.ThreadDeath異常

調(diào)用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();
    }
}

stop()方法以及作廢,因為如果強制讓線程停止有可能使一些清理性的工作得不到完成。另外一個情況就是對鎖定的對象進行了解鎖,導(dǎo)致數(shù)據(jù)得不到同步的處理,出現(xiàn)數(shù)據(jù)不一致的問題。

7. 釋放鎖的不良后果

使用stop()釋放鎖將會給數(shù)據(jù)造成不一致性的結(jié)果。如果出現(xiàn)這樣的情況,程序處理的數(shù)據(jù)就有可能遭到破壞,最終導(dǎo)致程序執(zhí)行的流程錯誤,一定要特別注意:

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());
    }
}

輸出結(jié)果:

b  aa

由于stop()方法以及在JDK中被標明為“過期/作廢”的方法,顯然它在功能上具有缺陷,所以不建議在程序張使用stop()方法。

8. 使用return停止線程

將方法interrupt()與return結(jié)合使用也能實現(xiàn)停止線程的效果:

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();
    }
}

輸出結(jié)果:

...
Time: 1467072288503
Time: 1467072288503
Time: 1467072288503
線程被停止了!

不過還是建議使用“拋異常”的方法來實現(xiàn)線程的停止,因為在catch塊中還可以將異常向上拋,使線程停止事件得以傳播。

到此這篇關(guān)于Java終止正在運行的線程的三種方法的文章就介紹到這了,更多相關(guān)Java終止正在運行的線程內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 詳解Java使用雙異步后如何保證數(shù)據(jù)一致性

    詳解Java使用雙異步后如何保證數(shù)據(jù)一致性

    這篇文章主要為大家詳細介紹了Java使用雙異步后如何保證數(shù)據(jù)一致性,文中的示例代碼講解詳細,具有一定的借鑒價值,有需要的小伙伴可以了解下
    2024-01-01
  • SpringBoot中集成串口通信的項目實踐

    SpringBoot中集成串口通信的項目實踐

    本文主要介紹了SpringBoot中集成串口通信,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-08-08
  • 通過Java設(shè)置Word頁面背景色過程詳解

    通過Java設(shè)置Word頁面背景色過程詳解

    這篇文章主要介紹了通過Java設(shè)置Word頁面背景色過程詳解,Word中可以針對不同文檔排版設(shè)計要求來設(shè)置背景設(shè)置顏色。常見的可設(shè)置單一顏色、漸變色或加載圖片來設(shè)置成背景。下面通過Java來設(shè)置以上3種Word頁面背景色,需要的朋友可以參考下
    2019-07-07
  • mybatis中mapper代理的生成過程全面分析

    mybatis中mapper代理的生成過程全面分析

    這篇文章主要為大家介紹了mybatis中mapper代理的生成過程全面分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-09-09
  • Java中如何計算一段程序的運行時間

    Java中如何計算一段程序的運行時間

    這篇文章主要介紹了Java中如何計算一段程序的運行時間問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • Java多線程基礎(chǔ)

    Java多線程基礎(chǔ)

    這篇文章主要介紹Java多線程基礎(chǔ),線程是進程的一個實體,是CPU調(diào)度和分派的基本單位,它是比進程更小的能獨立運行的基本單位,多線程指在單個程序中可以同時運行多個不同的線程執(zhí)行不同的任務(wù),下面來學習具體的詳細內(nèi)容
    2021-10-10
  • 詳解OpenAPI開發(fā)如何動態(tài)的添加接口實現(xiàn)

    詳解OpenAPI開發(fā)如何動態(tài)的添加接口實現(xiàn)

    這篇文章主要為大家介紹了OpenAPI開發(fā)如何動態(tài)的添加接口實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-04-04
  • 詳解Spring Boot 打包分離依賴JAR 和配置文件

    詳解Spring Boot 打包分離依賴JAR 和配置文件

    這篇文章主要介紹了Spring Boot 打包分離依賴JAR 和配置文件,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-11-11
  • JAVA正則表達式的基本使用教程

    JAVA正則表達式的基本使用教程

    這篇文章主要給大家介紹了關(guān)于JAVA正則表達式的基本使用教程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-03-03
  • java中JDeps命令使用

    java中JDeps命令使用

    jdeps是一個Java類依賴分析工具,用于分析Java應(yīng)用程序的依賴情況,包括類、包、模塊以及JDK內(nèi)部API的使用,本文就來詳細的介紹一下,感興趣的可以了解一下
    2024-09-09

最新評論