JUC学习-11-优雅的线程中断

JUC学习-11-线程中断

在执行完interrupt()方法后,只是给线程做了一个“打断的标记”,通知线程需要中断,并不会立即中断线程。

class TestIsInterrupted {
	public static void main(String[] args) {
		Thread t1 = new Thread() {
			@Override
			public void run() {
				while (true) {
					System.out.println("检测中");
				}
			}
		};
		t1.start();
		t1.interrupt();
	}
}

二、检查线程中断标志

检查中断标志位,判断当前线程是否被中断。

  public boolean isInterrupted() {
		return isInterrupted(false);
	}

静态方法。判断线程是否被中断,并清除当前中断状态

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

优雅的中断线程

class TestIsInterrupted {
	public static void main(String[] args) {
		Thread t1 = new Thread() {
			@Override
			public void run() {
				while (true) {
				 // 查看中断标记
                System.out.println(Thread.currentThread().isInterrupted());
				// 判断中断标识 并清除当前中断状态
					if (Thread.interrupted()) {
					System.out.println(Thread.currentThread().isInterrupted());
						break;
					}
					System.out.println("检测中");
				}
			}
		};
		t1.start();
		t1.interrupt();
	}
}

结果如下:

image

三、当出现InterruptedException 异常时,会清除中断标记 (变为false)

class TestIsInterrupted {
	public static void main(String[] args) {
		Thread t1 = new Thread() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// 当出现InterruptedException 会清除中断标记 false
						e.printStackTrace();
					}
					// 查看中断标记
					System.out.println(Thread.currentThread().isInterrupted());
					if (Thread.interrupted()) {
						System.out.println(Thread.currentThread().isInterrupted());
						break;
					}
					System.out.println("检测中");
				}
			}
		};
		t1.start();
		t1.interrupt();
	}
}

结果如下:

image

抛出异常后 再次加上中断标志(true)

class TestIsInterrupted {
	public static void main(String[] args) {
		Thread t1 = new Thread() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// 当出现InterruptedException 会清除中断标记 false
						e.printStackTrace();
						// 再次加上中断标记
						Thread.currentThread().interrupt();
					}
					// 查看中断标记
					System.out.println(Thread.currentThread().isInterrupted());
					if (Thread.interrupted()) {
						System.out.println(Thread.currentThread().isInterrupted());
						break;
					}
					System.out.println("检测中");
				}
			}
		};
		t1.start();
		t1.interrupt();
	}
}

结果如下:

image

posted @ 2025-07-07 14:20  skystrivegao  阅读(9)  评论(0)    收藏  举报