一,介紹
本文記錄JAVA多線程中的中斷機(jī)制的一些知識(shí)點(diǎn)。主要是stop方法、interrupted()與isInterrupted()方法的區(qū)別,并從源代碼的實(shí)現(xiàn)上進(jìn)行簡(jiǎn)單分析。
JAVA中有3種方式可以終止正在運(yùn)行的線程
①線程正常退出,即run()方法執(zhí)行完畢了
②使用Thread類(lèi)中的stop()方法強(qiáng)行終止線程。但stop()方法已經(jīng)過(guò)期了,不推薦使用
③使用中斷機(jī)制
線程正常退出沒(méi)有什么東東,中斷機(jī)制下面詳細(xì)介紹,先看下stop()方法的源代碼,關(guān)鍵是源代碼上的注釋。它解釋了為什么stop()不安全,stop()方法停止的是哪個(gè)線程?
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
/** * Forces the thread to stop executing. * <p> * If there is a security manager installed, its <code>checkAccess</code> * method is called with <code>this</code> * as its argument. This may result in a * <code>SecurityException</code> being raised (in the current thread). * <p> * If this thread is different from the current thread (that is, the current * thread is trying to stop a thread other than itself), the * security manager's <code>checkPermission</code> method (with a * <code>RuntimePermission("stopThread")</code> argument) is called in * addition. * Again, this may result in throwing a * <code>SecurityException</code> (in the current thread). * <p> * The thread represented by this thread is forced to stop whatever * it is doing abnormally and to throw a newly created * <code>ThreadDeath</code> object as an exception. * <p> * It is permitted to stop a thread that has not yet been started. * If the thread is eventually started, it immediately terminates. * <p> * An application should not normally try to catch * <code>ThreadDeath</code> unless it must do some extraordinary * cleanup operation (note that the throwing of * <code>ThreadDeath</code> causes <code>finally</code> clauses of * <code>try</code> statements to be executed before the thread * officially dies). If a <code>catch</code> clause catches a * <code>ThreadDeath</code> object, it is important to rethrow the * object so that the thread actually dies. * <p> * The top-level error handler that reacts to otherwise uncaught * exceptions does not print out a message or otherwise notify the * application if the uncaught exception is an instance of * <code>ThreadDeath</code>. * * @exception SecurityException if the current thread cannot * modify this thread. * @see #interrupt() * @see #checkAccess() * @see #run() * @see #start() * @see ThreadDeath * @see ThreadGroup#uncaughtException(Thread,Throwable) * @see SecurityManager#checkAccess(Thread) * @see SecurityManager#checkPermission * @deprecated This method is inherently unsafe. Stopping a thread with * Thread.stop causes it to unlock all of the monitors that it * has locked (as a natural consequence of the unchecked * <code>ThreadDeath</code> exception propagating up the stack). If * any of the objects previously protected by these monitors were in * an inconsistent state, the damaged objects become visible to * other threads, potentially resulting in arbitrary behavior. Many * uses of <code>stop</code> should be replaced by code that simply * modifies some variable to indicate that the target thread should * stop running. The target thread should check this variable * regularly, and return from its run method in an orderly fashion * if the variable indicates that it is to stop running. If the * target thread waits for long periods (on a condition variable, * for example), the <code>interrupt</code> method should be used to * interrupt the wait. * For more information, see * <a href="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why * are Thread.stop, Thread.suspend and Thread.resume Deprecated?</a>. */ @Deprecated public final void stop() { stop( new ThreadDeath()); } |
上面注釋,第9行到第16行表明,stop()方法可以停止“其他線程”。執(zhí)行thread.stop()方法這條語(yǔ)句的線程稱為當(dāng)前線程,而“其他線程”則是 調(diào)用thread.stop()方法的對(duì)象thread所代表的線程。
如:
1
2
3
4
5
6
|
public static void main(String[] args) { MyThread thread = new MyThread... //..... thread.stop(); //.... } |
在main方法中,當(dāng)前線程就是main線程。它執(zhí)行到第4行,想把“其他線程”thread“ 給停止。這個(gè)其他線程就是MyThread類(lèi) new 的thread對(duì)象所表示的線程。
第21行至23行表明,可以停止一個(gè)尚未started(啟動(dòng))的線程。它的效果是:當(dāng)該線程啟動(dòng)后,就立馬結(jié)束了。
第48行以后的注釋,則深刻表明了為什么stop()方法被棄用!為什么它是不安全的。
比如說(shuō),threadA線程擁有了監(jiān)視器,這些監(jiān)視器負(fù)責(zé)保護(hù)某些臨界資源,比如說(shuō)銀行的轉(zhuǎn)賬的金額。當(dāng)正在轉(zhuǎn)賬過(guò)程中,main線程調(diào)用 threadA.stop()方法。結(jié)果導(dǎo)致監(jiān)視器被釋放,其保護(hù)的資源(轉(zhuǎn)賬金額)很可能出現(xiàn)不一致性。比如,A賬戶減少了100,而B(niǎo)賬戶卻沒(méi)有增加100
二,中斷機(jī)制
JAVA中如何正確地使用中斷機(jī)制的細(xì)節(jié)太多了。interrupted()方法與 isInterrupted()方法都是反映當(dāng)前線程的是否處于中斷狀態(tài)的。
①interrupted()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
/** * Tests whether the current thread has been interrupted. The * <i>interrupted status</i> of the thread is cleared by this method. In * other words, if this method were to be called twice in succession, the * second call would return false (unless the current thread were * interrupted again, after the first call had cleared its interrupted * status and before the second call had examined it). * * <p>A thread interruption ignored because a thread was not alive * at the time of the interrupt will be reflected by this method * returning false. * * @return <code>true</code> if the current thread has been interrupted; * <code>false</code> otherwise. * @see #isInterrupted() * @revised . */ public static boolean interrupted() { return currentThread().isInterrupted( true ); } |
從源碼的注釋中看出,它測(cè)試的是當(dāng)前線程(current thread)的中斷狀態(tài),且這個(gè)方法會(huì)清除中斷狀態(tài)。
②isInterrupted()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
/** * Tests whether this thread has been interrupted. The <i>interrupted * status</i> of the thread is unaffected by this method. * * <p>A thread interruption ignored because a thread was not alive * at the time of the interrupt will be reflected by this method * returning false. * * @return <code>true</code> if this thread has been interrupted; * <code>false</code> otherwise. * @see #interrupted() * @revised . */ public boolean isInterrupted() { return isInterrupted( false ); } |
從源碼注釋中可以看出,isInterrupted()方法不會(huì)清除中斷狀態(tài)。
③interrupted()方法與 isInterrupted()方法的區(qū)別
從源代碼可以看出,這兩個(gè)方法都是調(diào)用的isInterrupted(boolean ClearInterrupted),只不過(guò)一個(gè)帶的參數(shù)是true,另一個(gè)帶的參數(shù)是false。
1
2
3
4
5
6
|
/** * Tests if some Thread has been interrupted. The interrupted state * is reset or not based on the value of ClearInterrupted that is * passed. */ private native boolean isInterrupted( boolean ClearInterrupted); |
因此,第一個(gè)區(qū)別就是,一個(gè)會(huì)清除中斷標(biāo)識(shí)位,另一個(gè)不會(huì)清除中斷標(biāo)識(shí)位。
再分析源碼,就可以看出第二個(gè)區(qū)別在return 語(yǔ)句上:
1
2
3
4
5
6
7
|
public static boolean interrupted() { return currentThread().isInterrupted( true ); } /************************/ public boolean isInterrupted() { return isInterrupted( false ); } |
interrupted()測(cè)試的是當(dāng)前的線程的中斷狀態(tài)。而isInterrupted()測(cè)試的是調(diào)用該方法的對(duì)象所表示的線程。一個(gè)是靜態(tài)方法(它測(cè)試的是當(dāng)前線程的中斷狀態(tài)),一個(gè)是實(shí)例方法(它測(cè)試的是實(shí)例對(duì)象所表示的線程的中斷狀態(tài))。
下面用個(gè)具體的例子來(lái)更進(jìn)一步地闡明這個(gè)區(qū)別。
有一個(gè)自定義的線程類(lèi)如下:
1
2
3
4
5
6
7
8
9
|
public class MyThread extends Thread { @Override public void run() { super .run(); for ( int i = ; i < ; i++) { System.out.println( "i=" + (i + )); } } } |
先看interrupted()方法的示例:
1
2
3
4
5
6
7
8
9
10
11
|
public class Run { public static void main(String[] args) { try { MyThread thread = new MyThread(); thread.start(); Thread.sleep(); thread.interrupt(); //Thread.currentThread().interrupt(); System.out.println( "是否停止?=" +thread.interrupted()); //false System.out.println( "是否停止?=" +thread.interrupted()); //false main線程沒(méi)有被中斷!!! //...... |
第5行啟動(dòng)thread線程,第6行使main線程睡眠1秒鐘從而使得thread線程有機(jī)會(huì)獲得CPU執(zhí)行。
main線程睡眠1s鐘后,恢復(fù)執(zhí)行到第7行,請(qǐng)求中斷 thread線程。
第9行測(cè)試線程是否處于中斷狀態(tài),這里測(cè)試的是哪個(gè)線程呢???答案是main線程。因?yàn)椋?/p>
(1)interrupted()測(cè)試的是當(dāng)前的線程的中斷狀態(tài)
(2)main線程執(zhí)行了第9行語(yǔ)句,故main線程是當(dāng)前線程
再看isInterrupted()方法的示例:
1
2
3
4
5
6
7
8
|
public class Run { public static void main(String[] args) { try { MyThread thread = new MyThread(); thread.start(); Thread.sleep(); thread.interrupt(); System.out.println( "是否停止?=" +thread.isInterrupted()); //true |
在第8行,是thread對(duì)象調(diào)用的isInterrupted()方法。因此,測(cè)試的是thread對(duì)象所代表的線程的中斷狀態(tài)。由于在第7行,main線程請(qǐng)求中斷 thread線程,故在第8行的結(jié)果為: true