java线程的interrupt

在Java中,可以使用Thread对象的interrupt()方法中断线程,并通过isInterrupted()检查中断状态。当线程被阻塞在特定方法时,中断会抛出InterruptedException并清除中断状态。代码示例展示了如何在不同线程中检测和处理中断。
摘要由CSDN通过智能技术生成

在Java中,可以通过Thread对象的interrupt()方法来中断对象引用的线程,通过Thread类的静态方法interrupted()测试当前线程的中断状态,通过Thread对象的isInterrupted()方法测试对象引用的线程的中断状态。
如果线程被阻塞在Object类的wait(), wait(long), 或者 wait(long, int) 方法,或者被阻塞在Thread类的join(), join(long), join(long, int), sleep(long), 或者sleep(long, int)方法,那么中断本线程后,本线程的中断状态被清除,并且本线程将收到一个InterruptedException异常。

代码示例:

package com.thb;

public class Test2 {
	
	public static void main(String[] args) {
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				try {					
					System.out.println("<在another线程中探测> 刚进来," + Thread.currentThread().getName() + " interrupted :" + Thread.currentThread().isInterrupted());
					// 睡眠5秒钟
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					// 中断状态被清除
					System.out.println("<在another线程中探测> 捕获InterruptedException后," + Thread.currentThread().getName() + "interrupted :" + Thread.currentThread().isInterrupted());					
				}
				
			}
		}, "another");
		
		t.start();

		// 此时线程another的中断状态应该是false
		System.out.println("<在主线程中探测>中断another线程前," + t.getName() + " interrupted: " + t.isInterrupted());

		// 主动中断线程another
		t.interrupt();
		System.out.println("<在主线程中探测>中断another线程后," + t.getName() + " interrupted: " + t.isInterrupted());
	}
}

一次运行输出的结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值