一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Java多線程中斷機制三種方法及示例

Java多線程中斷機制三種方法及示例

2021-02-04 12:07五月的倉頡 Java教程

這篇文章主要介紹了Java多線程中斷機制三種方法及示例,向大家分享了這三種方法的介紹幾代碼示例,具有一定參考價值,需要的朋友可以了解下。

概述

之前講解Thread類中方法的時候,interrupt()、interrupted()、isInterrupted()三個方法沒有講得很清楚,只是提了一下。現在把這三個方法同一放到這里來講,因為這三個方法都涉及到多線程的一個知識點----中斷機制

Java沒有提供一種安全、直接的方法來停止某個線程,而是提供了中斷機制。中斷機制是一種協作機制,也就是說通過中斷并不能直接終止另一個線程,而需要被中斷的線程自己處理。有個例子舉個蠻好,就像父母叮囑出門在外的子女要注意身體一樣,父母說了,但是子女是否注意身體、如何注意身體,還是要看自己。

中斷機制也是一樣的,每個線程對象里都有一個標識位表示是否有中斷請求(當然JDK的源碼是看不到這個標識位的,是虛擬機線程實現層面的),代表著是否有中斷請求。

三個中斷方法

上面說了,中斷標識位是JDK源碼看不到的,是虛擬機線程實現層面的。下面結合代碼逐一看一下這三個方法的作用,以及為什么中斷標識位是虛擬機實現層面的:

1、interrupt()

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void interrupt() {
  if (this != Thread.currentThread())
    checkAccess();
 
  synchronized (blockerLock) {
    Interruptible b = blocker;
    if (b != null) {
    interrupt0();    // Just to set the interrupt flag
    b.interrupt();
    return;
    }
  }
  interrupt0();
  }

結果

?
1
2
3
4
5
6
/* Some private helper methods */
private native void setPriority0(int newPriority);
private native void stop0(Object o);
private native void suspend0();
private native void resume0();
private native void interrupt0();

分兩部分看:

(1)第一部分的第8行注釋說得很清楚了,interrupt0()方法的作用是"Just to set the interrupt flag",即方法的作用僅僅是設置中斷標識位

(2)第二部分的第6行就是interrupt0()方法的原型,由于方法是被native修飾的,很明顯這是一個本地方法,是Java虛擬機實現的

2、isInterrupted()

方法唯一的作用只是測試線程是否已經中斷,中斷標識位的狀態并不受到該方法的影響,看一下Java是如何實現這個方法的:

?
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 6.0
 */
public boolean isInterrupted() {
return isInterrupted(false);
}
?
1
private native boolean isInterrupted(boolean ClearInterrupted);

注意一下第一部分的第2行和第3行,"The interrupted statis of the thread is unaffected by this method",即線程的中斷狀態不受到這個方法的影響。最終調用的是isInterrupted(boolean ClearInterrupted),這個方法是一個native的,看得出也是Java虛擬機實現的。方法的參數ClearInterrupted,顧名思義,清除中斷標識位,這里傳遞false,明顯就是不清除

3、interrupted()

方法的作用是測試當前線程是否已經中斷,線程的中斷標識位由該方法清除。換句話說,連續兩次調用該方法的返回值必定是false。看一下這個方法是如何實現的:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
 * 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 6.0
 */
public static boolean interrupted() {
return currentThread().isInterrupted(true);
?
1
private native boolean isInterrupted(boolean ClearInterrupted);

同樣,第2行和第3行的注釋已經寫得很清楚了,"Theinterruptedstatusofthethreadisclearedbythismethod",即線程的中斷狀態由此方法清除。另外,interrupted()方法和isInterrupted()方法調用的是同一個native方法,無非這個方法傳入的是true,表示清除中斷標識位

此外,JDKAPI中有些類的方法也可能會調用中斷,比如FutureTask的cancel,如果傳入true則會在正在運行的異步任務上調用interrupt()方法,又如ThreadPoolExecutor中的shutdownNow方法會遍歷線程池中的工作線程并調用線程的interrupt()方法。這些場景下只要代碼沒有對中斷作出響應,那么任務將一直執行下去。

中斷處理時機

這其實是一個很寬泛的、沒有標注答案的話題。顯然,作為一種協作機制,不會強求被中斷的線程一定要在某個點進行中斷處理。實際上,被中斷線程只需要在合適的時候處理即可,如果沒有合適的時間點,甚至可以不處理。"合適的時間點"就和業務邏輯密切相關了。

處理時機決定著程序的效率和響應的靈敏度。頻繁的檢查中斷可能會導致程序執行效率低下,較少的檢查則可能導致中斷請求得不到及時響應。在實際場景中,如果性能指標比較關鍵,可能需要建立一個測試模型來分析最佳的中斷檢測點,以平衡性能和響應靈敏性。

線程中斷舉例

寫了這么多理論,寫一個例子來演示一下中斷:

?
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
public static void main(String[] args) throws Exception
{
  Runnable runnable = new Runnable()
  {
    public void run()
    {
      while (true)
      {
        if (Thread.currentThread().isInterrupted())
        {
          System.out.println("線程被中斷了");
          return ;
        }
        else
        {
          System.out.println("線程沒有被中斷");
        }
      }
    }
  };
  Thread t = new Thread(runnable);
  t.start();
  Thread.sleep(3000);
  t.interrupt();
  System.out.println("線程中斷了,程序到這里了");
}

看一下運行結果:

?
1
2
3
4
5
6
7
8
...
線程沒有被中斷
線程沒有被中斷
線程沒有被中斷
線程沒有被中斷
線程沒有被中斷
線程中斷了,程序到這里了
線程被中斷了

代碼分為以下幾步:

1、main函數起一個t線程

2、main函數3秒鐘之后給t線程打一個中斷標識位,表示t線程要中斷

3、t線程無限輪詢自己的中斷標識位,中斷了則打印、退出,否則一直運行

從控制臺上打印的語句看到,3秒鐘中斷后,打印出該打印的語句后,就停止了。那這種場景就是前面說的"頻繁地檢查",導致程序效率低下;那如果不頻繁地檢查呢,比如在while中的else分支中加上Thread.sleep(500),表示500ms即0.5s檢查一次,那這種場景就是前面說的"中斷得不到及時的響應"。

其實這個例子中,t線程完全可以不用去管這個中斷標識位的,不去檢查就好了,只管做自己的事情,這說明中斷標識位設不設置是別人的事情,處不處理是我自己的事情,沒有強制要求必須處理中斷。

但是,那些會拋出InterruptedException的方法要除外。像sleep、wait、notify、join,這些方法遇到中斷必須有對應的措施,可以直接在catch塊中處理,也可以拋給上一層。這些方法之所以會拋出InterruptedException就是由于Java虛擬機在實現這些方法的時候,本身就有某種機制在判斷中斷標識位,如果中斷了,就拋出一個InterruptedException。

總結

以上就是本文關于Java多線程中斷機制三種方法及示例的全部內容,希望對大家有所幫助。如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!

原文鏈接:http://www.cnblogs.com/xrq730/p/4856361.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 午夜在线a亚洲v天堂网2019 | 门房秦大爷最新章节阅读 | 日本免费在线观看 | 成年男人永久免费看片 | 99热com| 国产在线精品一区二区高清不卡 | 暖暖免费高清完整版观看日本 | 欧美特欧美特级一片 | 亚洲精品人成网在线播放影院 | 欧美极品摘花过程 | 俄罗斯烧性春三级k8播放 | 免费高清资源黄网站在线观看 | 福利视频一区青娱 | 日本三级s级在线播放 | 亚洲视频中文 | 91久久精品视频 | 视频一本大道香蕉久在线播放 | 成人观看免费观看视频 | 边摸边吃奶玩乳尖视频 | 欧美贵妇vs高跟办公室 | 亚洲美女aⅴ久久久91 | 精品女同一区二区三区免费站 | 精品综合久久久久久8888 | 大陆性出航 | 99精品在免费线视频 | 嗯啊好大好粗 | 小辣椒精品福利视频导航 | 视频在线91 | 双性小说肉 | 欧美高清无砖专区欧美精品 | 动漫美女被褥吸奶漫画漫画 | 99福利影院 | 男人桶女下面60分钟视频 | 亚洲精品有码在线观看 | 国产在线99 | 公交车强校花系列小说 | 国产午夜精品理论片 | 99午夜 | 午夜一个人在线观看完整版 | 日产精品卡一卡2卡三卡乱码工厂 | 男人女人叉叉叉 |