Java-Interrupt-中断信号

本文介绍了Java中的中断信号处理。当线程被中断时,如果它处于阻塞状态,会抛出InterruptedException;若线程正在运行,则仅设置中断标志位。通过示例代码展示了中断操作及其响应方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、中断信号Interrupt

1.如果线程处于阻塞状态会立马退出阻塞并抛出InterruptedException异常,线程可以通过捕获InterruptedException方法来做一定处理,然后让线程退出。

2.如果线程处于运行中则不受任何影响继续运行,仅仅将线程的中断标记设置为true。

2、示例代码

public class ThreadInterruptDemo {

	public static void main(String[] args) throws InterruptedException {
		// 模拟正常运行发出中断信号
		Thread threadOne = new Thread(new Runnable() {
			public void run() {
				Thread currentThread = Thread.currentThread();
				while (!currentThread.isInterrupted()) {
					System.out.println("Thread One 正在运行!");
				}
				System.out.println("Thread One 正常结束!" + currentThread.isInterrupted());
			}
		});
		// 模拟阻塞线程发出中断信号
		Thread threadTwo = new Thread(new Runnable() {
			public void run() {
				Thread currentThread = Thread.currentThread();
				while (!currentThread.isInterrupted()) {
					synchronized (currentThread) {
						try {
							currentThread.wait();
						} catch (Exception e) {
							e.printStackTrace(System.out);
							System.out.println("Thread Two 由于中断信号,异常结束!" + currentThread.isInterrupted());
						}
					}
				}
				System.out.println("Thread Two 正常结束!" + currentThread.isInterrupted());
			}
		});
		
		threadOne.start();
		threadTwo.start();
		Thread.sleep(2);
		System.out.println("两个线程正常运行,现在开始发出中断信号");
		threadOne.interrupt();
		threadTwo.interrupt();
		
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值