1. 程式人生 > >從頭認識java-17.2 線程中斷(interrupt)

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

detail 由於 main target thread code font 輸出 去掉

這一章節我們來討論一下線程中斷(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;

	@Override
	public 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 {

	@Override
	public 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;

	@Override
	public 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 block
					e.printStackTrace();
				}
			}
			i++;
		}
	}
}


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

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

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

文件夾

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