一、java中終止線程主要有三種方法:
①線程正常退出,即run()方法執(zhí)行完畢了
②使用Thread類(lèi)中的stop()(已過(guò)期不推薦使用)方法強(qiáng)行終止線程。
③使用中斷機(jī)制
t.stop()調(diào)用時(shí),終止線程,會(huì)導(dǎo)致該線程所持有的鎖被強(qiáng)制釋放,從而被其他線程所持有,因此有可能導(dǎo)致與預(yù)期結(jié)果不一致。下面使用中斷信號(hào)量中斷非阻塞狀態(tài)的線程中:
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
|
public class TestStopThread { public static void main(String[] args) throws InterruptedException { StopThread st = new StopThread(); st.setName( "線程st" ); st.start(); Thread.sleep( 3000 ); st.stopFlag(); Thread.sleep( 1000 ); System.out.println(st.getState()); } } class StopThread extends Thread { // 此變量必須加上volatile private volatile boolean stop = false ; @Override public void run() { // 判斷線程體是否運(yùn)行 while (!stop) { System.out.println( "線程StopThread正在運(yùn)行" ); long time = System.currentTimeMillis(); /* * 使用while循環(huán)模擬 sleep 方法,這里不要使用sleep,否則在阻塞時(shí)會(huì)拋 * InterruptedException異常而退出循環(huán),這樣while檢測(cè)stop條件就不會(huì)執(zhí)行, * 失去了意義。 */ while ((System.currentTimeMillis() - time < 1000 )) {} } System.out.println( "線程StopThread正在結(jié)束" ); } // 線程終止 public void stopFlag() { stop = true ; } } |
二、java線程中斷機(jī)制
下面看看Thread類(lèi)里的三個(gè)方法:
1. public static boolean interrupted():檢測(cè)當(dāng)前線程是否已經(jīng)中斷。線程的中斷狀態(tài)由該方法清除。如果連續(xù)兩次調(diào)用該方法,則第二次調(diào)用將返回 false(在第一次調(diào)用已清除了其中斷狀態(tài)之后,且第二次調(diào)用檢驗(yàn)完中斷狀態(tài)前,當(dāng)前線程再次中斷的情況除外)。
2. public boolean isInterrupted():測(cè)試線程是否已經(jīng)中斷。線程的中斷狀態(tài)不受該方法的影響。
3. public void interrupt(): 中斷線程。
interrupt()只是改變中斷狀態(tài)而已. interrupt()不會(huì)終止一個(gè)正在運(yùn)行的線程。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public class TestInterrupt1 { public static void main(String[] args) throws InterruptedException { Thread t = new MyThread(); t.start(); t.interrupt(); System.out.println( "調(diào)用線程的interrupt()方法" ); System.out.println( "線程的中斷狀態(tài):" +t.isInterrupted()); } static class MyThread extends Thread { public void run() { long time = System.currentTimeMillis(); System.out.println( "線程正在運(yùn)行" ); /* * 使用while循環(huán)模擬 sleep 方法,這里不要使用sleep,否則在阻塞時(shí)會(huì)拋 * InterruptedException異常而退出循環(huán)。 */ while ((System.currentTimeMillis() - time < 1000 )) {} System.out.println( "線程的中斷狀態(tài):" + Thread.interrupted()); System.out.println( "線程的中斷狀態(tài)被清除:" +isInterrupted()); while ((System.currentTimeMillis() - time < 5000 )) {} System.out.println( "線程運(yùn)行完成" ); } } } |
正常輸出:
1
2
3
4
5
6
|
調(diào)用線程的interrupt()方法 線程正在運(yùn)行 線程的中斷狀態(tài): true 線程的中斷狀態(tài): true 線程的中斷狀態(tài)被清除: false 線程運(yùn)行完成 |
實(shí)際上當(dāng)調(diào)用interrupt()方法的時(shí)候,只是設(shè)置了要中斷線程的中斷狀態(tài),而此時(shí)被中斷的線程的可以通過(guò)isInterrupted()或者是Thread.interrupted()方法判斷當(dāng)前線程的中斷狀態(tài)是否標(biāo)志為中斷。
調(diào)用線程的wait(), wait(long)或wait(long, int)會(huì)讓它進(jìn)入等待(阻塞)狀態(tài),或者調(diào)用線程的join(), join(long), join(long, int), sleep(long), sleep(long, int)也會(huì)讓它進(jìn)入阻塞狀態(tài)。若線程在阻塞狀態(tài)時(shí),調(diào)用了它的interrupt()方法,那么它的“中斷狀態(tài)”會(huì)被清除并且會(huì)收到一個(gè)InterruptedException異常。例如,線程通過(guò)wait()進(jìn)入阻塞狀態(tài),此時(shí)通過(guò)interrupt()中斷該線程;調(diào)用interrupt()會(huì)立即將線程的中斷標(biāo)記設(shè)為“true”,但是由于線程處于阻塞狀態(tài),所以該“中斷標(biāo)記”會(huì)立即被清除為“false”,同時(shí),會(huì)產(chǎn)生一個(gè)InterruptedException的異常。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public class InterruptTest extends Thread{ public static void main(String[] args) throws InterruptedException { InterruptTest t= new InterruptTest(); t.start(); Thread.sleep( 1000 ); t.interrupt(); } public void run(){ while (!Thread.interrupted()){ System.out.println( "Thread is running....." ); try { Thread.sleep( 5000 ); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } |
正常運(yùn)行結(jié)果:
系統(tǒng)復(fù)位。我們可以手動(dòng)的使用Thread.interrupted()來(lái)使當(dāng)前線程的中斷狀態(tài)系統(tǒng)復(fù)位(即清除中斷狀態(tài)),其實(shí)是在sleep,wait,join這些方法內(nèi)部會(huì)不斷檢查中斷狀態(tài)的值,而自己拋出的InterruptedException。
中斷:如果線程在調(diào)用Object類(lèi)的wait()、wait(long)或wait(long, int)方法,或者該類(lèi)的 join() 、join(long) 、join(long, int) 、sleep(long) 或 sleep(long, int) 方法過(guò)程中受阻,則其中斷狀態(tài)將被清除,它還將收到一個(gè) InterruptedException。
如果該線程在可中斷的通道(java.nio.channels.InterruptibleChannel)上的 I/O 操作中受阻,則該通道將被關(guān)閉,該線程的中斷狀態(tài)將被設(shè)置并且該線程將收到一個(gè) ClosedByInterruptException。
如果該線程在一個(gè) Selector (java.nio.channels.Selector) 中受阻,則該線程的中斷狀態(tài)將被設(shè)置,它將立即從選擇操作返回,并可能帶有一個(gè)非零值,就好像調(diào)用了選擇器的 wakeup 方法一樣。
如果以前的條件都沒(méi)有保存,則該線程的中斷狀態(tài)將被設(shè)置。
中斷一個(gè)不處于活動(dòng)狀態(tài)的線程不需要任何作用。
檢測(cè)中斷:如何檢測(cè)中斷決定于線程所做的事情。
如果線程調(diào)用可以拋出InterruptException的方法,則捕獲InterruptException,然后在catch塊中處理(通常是退出run方法以中斷線程)
如果調(diào)用其它方法,則可以在空閑時(shí)檢查T(mén)hread.interrupted以判斷是否收到中斷信號(hào),確認(rèn)收到中斷信號(hào)后進(jìn)行處理。可以拋出一個(gè)InterruptException從而和前一種處理方法保持一致
中斷狀態(tài):線程的中斷機(jī)制是使用中斷狀態(tài)這一內(nèi)部標(biāo)志實(shí)現(xiàn)的。中斷狀態(tài)在調(diào)用線程的interrupt()方法時(shí)被設(shè)置(參考上面的interrupt方法說(shuō)明)。
可以發(fā)現(xiàn),isInterrupted被聲明為native方法,取決于JVM底層的實(shí)現(xiàn)。調(diào)用線程的interrupt方法,并不能立即引發(fā)中斷,只是設(shè)置了JVM內(nèi)部的中斷標(biāo)記。因此,通過(guò)檢查中斷標(biāo)記,應(yīng)用程序可以做一些特殊操作,也可以完全忽略中斷。
實(shí)際上Thread.interrupt()方法實(shí)際上通過(guò)某種方式通知線程,并不會(huì)直接中止該線程。具體做什么事情由寫(xiě)代碼的人決定,通常我們會(huì)中止該線程。
三、一些不會(huì)拋出 InterruptedException 的線程阻塞操作
對(duì)于某些線程阻塞操作,JVM并不會(huì)自動(dòng)拋出InterruptedException異常。例如,某些I/O操作和內(nèi)部鎖操作。對(duì)于這類(lèi)操作,可以用其他方式模擬中斷:
1)java.io中的異步socket I/O
讀寫(xiě)socket的時(shí)候,InputStream和OutputStream的read和write方法會(huì)阻塞等待,但不會(huì)響應(yīng)java中斷。不過(guò),調(diào)用Socket的close方法后,被阻塞線程會(huì)拋出SocketException異常。
2)利用Selector實(shí)現(xiàn)的異步I/O
如果線程被阻塞于Selector.select(在java.nio.channels中),調(diào)用wakeup方法會(huì)引起ClosedSelectorException異常。
3)鎖獲取
如果線程在等待獲取一個(gè)內(nèi)部鎖,我們將無(wú)法中斷它。但是,利用Lock類(lèi)的lockInterruptibly方法,我們可以在等待鎖的同時(shí),提供中斷能力。
總結(jié)
以上就是本文關(guān)于java多線程中斷代碼詳解的全部?jī)?nèi)容,希望對(duì)大家有所幫助。有什么問(wèn)題可以隨時(shí)留言,小編會(huì)及時(shí)回復(fù)大家的。感謝朋友們對(duì)本站的支持!
原文鏈接:https://www.2cto.com/kf/201609/546958.html