最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JAVA多線程之中斷機制stop()、interrupted()、isInterrupted()

 更新時間:2016年05月01日 12:33:56   作者:hapjin  
這篇文章主要介紹了JAVA多線程之中斷機制stop()、interrupted()、isInterrupted()的相關資料,需要的朋友可以參考下

一,介紹

本文記錄JAVA多線程中的中斷機制的一些知識點。主要是stop方法、interrupted()與isInterrupted()方法的區(qū)別,并從源代碼的實現上進行簡單分析。

JAVA中有3種方式可以終止正在運行的線程

①線程正常退出,即run()方法執(zhí)行完畢了

②使用Thread類中的stop()方法強行終止線程。但stop()方法已經過期了,不推薦使用

③使用中斷機制

線程正常退出沒有什么東東,中斷機制下面詳細介紹,先看下stop()方法的源代碼,關鍵是源代碼上的注釋。它解釋了為什么stop()不安全,stop()方法停止的是哪個線程?

/**
* 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()方法這條語句的線程稱為當前線程,而“其他線程”則是 調用thread.stop()方法的對象thread所代表的線程。

如:

public static void main(String[] args) {
MyThread thread = new MyThread...
//.....
thread.stop();
//....
}

在main方法中,當前線程就是main線程。它執(zhí)行到第4行,想把“其他線程”thread“ 給停止。這個其他線程就是MyThread類 new 的thread對象所表示的線程。

第21行至23行表明,可以停止一個尚未started(啟動)的線程。它的效果是:當該線程啟動后,就立馬結束了。

第48行以后的注釋,則深刻表明了為什么stop()方法被棄用!為什么它是不安全的。

比如說,threadA線程擁有了監(jiān)視器,這些監(jiān)視器負責保護某些臨界資源,比如說銀行的轉賬的金額。當正在轉賬過程中,main線程調用 threadA.stop()方法。結果導致監(jiān)視器被釋放,其保護的資源(轉賬金額)很可能出現不一致性。比如,A賬戶減少了100,而B賬戶卻沒有增加100

二,中斷機制

JAVA中如何正確地使用中斷機制的細節(jié)太多了。interrupted()方法與 isInterrupted()方法都是反映當前線程的是否處于中斷狀態(tài)的。

①interrupted()

/**
* 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);
}

從源碼的注釋中看出,它測試的是當前線程(current thread)的中斷狀態(tài),且這個方法會清除中斷狀態(tài)。

②isInterrupted()

/**
* 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()方法不會清除中斷狀態(tài)。

③interrupted()方法與 isInterrupted()方法的區(qū)別

從源代碼可以看出,這兩個方法都是調用的isInterrupted(boolean ClearInterrupted),只不過一個帶的參數是true,另一個帶的參數是false。

/**
* 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);

因此,第一個區(qū)別就是,一個會清除中斷標識位,另一個不會清除中斷標識位。

再分析源碼,就可以看出第二個區(qū)別在return 語句上:

public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
/************************/
public boolean isInterrupted() {
return isInterrupted(false);
}

interrupted()測試的是當前的線程的中斷狀態(tài)。而isInterrupted()測試的是調用該方法的對象所表示的線程。一個是靜態(tài)方法(它測試的是當前線程的中斷狀態(tài)),一個是實例方法(它測試的是實例對象所表示的線程的中斷狀態(tài))。

下面用個具體的例子來更進一步地闡明這個區(qū)別。

有一個自定義的線程類如下:

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

先看interrupted()方法的示例:

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線程沒有被中斷!!!
      //......

第5行啟動thread線程,第6行使main線程睡眠1秒鐘從而使得thread線程有機會獲得CPU執(zhí)行。

main線程睡眠1s鐘后,恢復執(zhí)行到第7行,請求中斷 thread線程。

第9行測試線程是否處于中斷狀態(tài),這里測試的是哪個線程呢???答案是main線程。因為:

(1)interrupted()測試的是當前的線程的中斷狀態(tài)

(2)main線程執(zhí)行了第9行語句,故main線程是當前線程

再看isInterrupted()方法的示例:

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對象調用的isInterrupted()方法。因此,測試的是thread對象所代表的線程的中斷狀態(tài)。由于在第7行,main線程請求中斷 thread線程,故在第8行的結果為: true

相關文章

  • Java字符串排序的幾種實現方式

    Java字符串排序的幾種實現方式

    這篇文章主要給大家介紹了關于Java字符串排序的幾種實現方式, 使用Java平臺進行字符串排序被認為是一件簡單的工作,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2023-07-07
  • Java面試重點中的重點之Elasticsearch核心原理

    Java面試重點中的重點之Elasticsearch核心原理

    ElasticSearch是一個基于Lucene的搜索引擎,是用Java語言開發(fā)的,能夠達到實時搜索,穩(wěn)定,可靠,快速,安裝使用方便,作為Apache許可條款下的開放源碼發(fā)布,是一種流行的企業(yè)級搜索引擎,是最受歡迎的企業(yè)搜索引擎
    2022-01-01
  • MySql多表查詢 事務及DCL

    MySql多表查詢 事務及DCL

    這篇文章主要介紹了MySql多表查詢 、事務、DCL的相關資料,需要的朋友可以參考下面文章內容
    2021-09-09
  • elasticsearch kibana簡單查詢講解

    elasticsearch kibana簡單查詢講解

    今天小編就為大家分享一篇關于elasticsearch kibana簡單查詢講解,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-02-02
  • SpringBoot整合Netty的流程步驟

    SpringBoot整合Netty的流程步驟

    Netty是一個基于Java的開源網絡應用框架,它提供了高性能、異步事件驅動的網絡編程能力,Netty旨在幫助開發(fā)者構建高性能、高可靠性的網絡應用程序,本文給大家詳細介紹了SpringBoot整合Netty的流程步驟,需要的朋友可以參考下
    2023-09-09
  • 使用Swagger實現接口版本號管理方式

    使用Swagger實現接口版本號管理方式

    這篇文章主要介紹了使用Swagger實現接口版本號管理方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • SpringBoot查詢PGSQL分表后的數據的代碼示例

    SpringBoot查詢PGSQL分表后的數據的代碼示例

    數據庫用的pgsql,在表數據超過100w條的時候執(zhí)行定時任務進行了分表,分表后表名命名為原的表名后面拼接時間,但是我在java業(yè)務代碼中,我想查詢之前的那條數據就查不到了,本文給大家介紹了SpringBoot中如何查詢PGSQL分表后的數據,需要的朋友可以參考下
    2024-05-05
  • SpringMVC中解決@ResponseBody注解返回中文亂碼問題

    SpringMVC中解決@ResponseBody注解返回中文亂碼問題

    這篇文章主要介紹了SpringMVC中解決@ResponseBody注解返回中文亂碼問題, 小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-04-04
  • Win10 Java jdk14.0.2安裝及環(huán)境變量配置詳細教程

    Win10 Java jdk14.0.2安裝及環(huán)境變量配置詳細教程

    這篇文章主要介紹了Win10 Java jdk14.0.2安裝及環(huán)境變量配置,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-08-08
  • Java 得到集合中所有子集

    Java 得到集合中所有子集

    本文主要介紹了Java 得到集合中所有子集的方法。具有很好的參考價值,下面跟著小編一起來看下吧
    2017-02-02

最新評論

穆棱市| 长阳| 云龙县| 达拉特旗| 平江县| 拉萨市| 乌兰察布市| 徐闻县| 大厂| 天镇县| 沅江市| 西宁市| 新巴尔虎右旗| 庆阳市| 赤城县| 城步| 盈江县| 富顺县| 南康市| 金坛市| 南和县| 望谟县| 泰宁县| 镇沅| 马龙县| 修武县| 山阴县| 资阳市| 云和县| 灵石县| 自贡市| 岢岚县| 公安县| 连南| 海城市| 巴南区| 阿巴嘎旗| 宜宾市| 申扎县| 固阳县| 高安市|