太難了!面試官要我停止一個正在運行的線程!

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

在java中有以下3種方法可以終止正在運行的線程:

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

1. 停止不了的線程

interrupt()方法的使用效果並不像for+break語句那樣,馬上就停止循環。調用interrupt方法是在當前線程中打了一個停止標誌,並不是真的停止線程。

{
{
.run();
( i=; i System.out.println(+(i+));
}
}
}
{
{
Thread thread = MyThread();
thread.start();
{
Thread.sleep();
thread.interrupt();
} (InterruptedException e) {
e.printStackTrace();
}
}
}

輸出結果:

...
i=499994
i=499995
i=499996
i=499997
i=499998
i=499999
i=500000
2. 判斷線程是否停止狀態

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

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

那麼這兩個方法有什麼圖區別呢?

我們先來看看this.interrupted()方法的解釋:測試當前線程是否已經中斷,當前線程是指運行this.interrupted()方法的線程。

{
{
.run();
( i=; i i++;
}
}
}
{
{
Thread thread = MyThread();
thread.start();
{
Thread.sleep();
thread.interrupt();
System.out.println( + thread.interrupted());


System.out.println( + thread.interrupted());
} (InterruptedException e) {
e.printStackTrace();
}
}
}

運行結果:

??
??

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

(" 1??" + ());
(" 2??" + ());

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

如何使main線程產生中斷效果呢?

{
{
Thread.currentThread().interrupt();
System..println( + Thread.interrupted());
System..println( + Thread.interrupted());
System..println();
}
}

運行效果為:

??


??

方法interrupted()的確判斷出當前線程是否是停止狀態。但為什麼第2個布爾值是false呢?官方幫助文檔中對interrupted方法的解釋:

測試當前線程是否已經中斷。線程的中斷狀態由該方法清除。

換句話說,如果連續兩次調用該方法,則第二次調用返回false。

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

{
{
Thread thread = MyThread();
thread.start();
thread.interrupt();
System..println( + thread.isInterrupted());
System..println( + thread.isInterrupted());
}
}

運行結果:

??
??

isInterrupted()併為清除狀態,所以打印了兩個true。


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

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

{
{
.run();
( i=; i (.interrupted()) {
System.out.println();
;
}
System.out.println(+(i+));
}
}
}
{
{
Thread thread = MyThread();
thread.start();
{
Thread.sleep();
thread.interrupt();
} (InterruptedException e) {
e.printStackTrace();
}
}
}

運行結果:

...
i=202053
i=202054
i=202055
i=202056
線程已經終止, for循環不再執行

上面的示例雖然停止了線程,但如果for語句下面還有語句,還是會繼續運行的。看下面的例子:

public {
public void run(){
.run();
(int i=; i (.interrupted()) {
.out.println();
;
}


.out.println(+(i+));
}
.out.println();
}
}

使用Run.java執行的結果是:

...
i=180136
i=180137
i=180138
i=180139
線程已經終止, for循環不再執行
這是for循環外面的語句,也會被執行

如何解決語句繼續運行的問題呢?看一下更新後的代碼:

public {
public void run(){
.run();
{
(int i=; i (.interrupted()) {
.out.println();
();
}
.out.println(+(i+));
}
.out.println();
} ( e) {
.out.println();
e.printStackTrace();
}
}
}

使用Run.java運行的結果如下:

...
i=203798


i=203799
i=203800
線程已經終止, for循環不再執行
進入MyThread.java類中的catch了。。。
java.lang.InterruptedException
at thread.MyThread.run(MyThread.java:13)
4. 在沉睡中停止

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

public {
public void run(){
.run();
{
.out.println();
.sleep();
.out.println();
} ( e) {
.out.println( + .isInterrupted());
e.printStackTrace();
}
}
}

使用Run.java運行的結果是:

線程開始。。。
在沉睡中被停止, 進入, 調用()方法的結果是:
:
( )
(

從打印的結果來看, 如果在sleep狀態下停止某一線程,會進入catch語句,並且清除停止狀態值,使之變為false。

前一個實驗是先sleep然後再用interrupt()停止,與之相反的操作在學習過程中也要注意:

{
{
super.run();
{
System..println();
( i=; i System..println( + i);
}
Thread.sleep();
System..println();
} (InterruptedException e) {
System..println();
e.printStackTrace();
}
}
}
{
{
Thread thread = MyThread();
thread.start();
thread.interrupt();
}
}

運行結果:

i=9998
i=9999
先停止,再遇到sleep,進入catch異常
at java.lang.Thread.sleep(Native Method)
at thread.MyThread.run(MyThread.java:15)
5. 能停止的線程---暴力停止

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

{
i = ;
{
.run();
{
(){
System.out.println( + i);
i++;
Thread.sleep();
}


} (InterruptedException e) {
e.printStackTrace();
}
}
}
{
{
Thread thread = MyThread();
thread.start();
Thread.sleep();
thread.stop();
}
}

運行結果:

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異常

調用stop()方法時會拋出java.lang.ThreadDeath異常,但是通常情況下,此異常不需要顯示地捕捉。

{
i = ;
{
.run();
{
.stop();
} (ThreadDeath e) {
System.out.println();
e.printStackTrace();
}
}
}
{
{


Thread thread = MyThread();
thread.start();
}
}

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

輸出結果:

b aa

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

輸出結果:

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

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

來源:https://urlify.cn/32IFju


分享到:


相關文章: