從頭認識java-17.2 線程中斷(interrupt)

來源:互聯網
上載者:User

標籤:space   try   string   stat   targe   線程中斷   new   net   package   

這一章節我們來討論一下線程中斷(interrupt)。

1.什麼是線程中斷(interrupt)?

就是在多線程執行的時候,我們給線程貼上一個中斷的標記。可是不要求線程終止。

 

2.範例:

中斷的範例:

package com.ray.ch17;public class Test2 {public static void main(String[] args) {PrintA printA = new PrintA();Thread threadA = new Thread(printA);threadA.start();}}class PrintA implements Runnable {private static int i = 0;@Overridepublic void run() {while (!Thread.currentThread().isInterrupted()) {System.out.println("PrintA");if (i == 2) {Thread.currentThread().interrupt();}i++;}}}


輸出:

PrintA
PrintA
PrintA

不中斷的範例:

package com.ray.ch17;public class Test2 {public static void main(String[] args) {PrintB printB = new PrintB();Thread threadB = new Thread(printB);threadB.start();}}class PrintB implements Runnable {@Overridepublic void run() {for (int i = 0; i < 5; i++) {System.out.println("PrintB");Thread.currentThread().interrupt();}}}


輸出:

PrintB
PrintB
PrintB
PrintB
PrintB

由上面的兩個範例我們能夠看出,interrupt僅僅是貼上一個中斷的標記,不會強制中斷。

 

3.interrupt與sleep的衝突

由於當使用sleep在interrupt之後使用,sleep將會去掉interrupt這個標記

衝突代碼。以下的代碼將會無限輸出:

package com.ray.ch17;public class Test2 {public static void main(String[] args) {PrintA printA = new PrintA();Thread threadA = new Thread(printA);threadA.start();}}class PrintA implements Runnable {private static int i = 0;@Overridepublic void run() {while (!Thread.currentThread().isInterrupted()) {System.out.println("PrintA");if (i == 2) {Thread.currentThread().interrupt();try {Thread.currentThread().sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}i++;}}}


總結:這一章節主要介紹線程中斷(interrupt)。

 

這一章節就到這裡,謝謝。

-----------------------------------

檔案夾

 

從頭認識java-17.2 線程中斷(interrupt)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.