標籤: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)