Java并发基础(2)——中断线程

目录

一、如何中断线程

1.1 interrupt()

1.2 isInterrupted() 

1.3 static方法interrupted()

二、demo

2.1 interrupt()和 isInterrupted() 

2.2 InterruptedException的demo


一、如何中断线程

1.1 interrupt()

interrupt() 中断一个线程,但不是强行关闭这个线程,只是跟这个线程打个招呼,将线程的中断标志位置为true,线程是否中断,由线程本身决定。

1.2 isInterrupted() 

isInterrupted() 判定当前线程是否处于中断状态。

1.3 static方法interrupted()

static方法interrupted() 判定当前线程是否处于中断状态,同时中断标志位改为false。

二、demo

2.1 interrupt()和 isInterrupted() 

public class InterruptedDemo {
	private static class UseThread extends Thread{	
		@Override
		public void run() {
			String threadName = Thread.currentThread().getName();
			while(!isInterrupted()) {
				System.out.println(threadName+"正在运行,它的中断标志位" + isInterrupted()  );
			}
			System.out.println(threadName+"被中断,它的中断标志位" + isInterrupted()  );
		}
	}

	public static void main(String[] args) throws InterruptedException {
		Thread myThread = new UseThread();
		myThread.start();
		Thread.sleep(10);
		myThread.interrupt();
	}
}

运行结果

注意:上面代码是线程是extends Thread类的,我们使用isInterrupted()方法判断当前线程是否处于中断状态

如果线程是implements Runnable,则要通过Thread.currentThread().isInterrupted()(也就是static方法interrupted() )来当前线程是否处于中断状态

另外一个需要注意的地方

方法里如果抛出InterruptedException,线程的中断标志位会被复位成false

此时如果确实是需要中断线程,要求我们自己在catch语句块里再次调用interrupt()

2.2 InterruptedException的demo

public class HasInterrputException {
	private static class MyThread extends Thread{
		
		@Override
		public void run() {
			String threadName = Thread.currentThread().getName();
			while(!isInterrupted()) {
				try {
					System.out.println("子线程开始运行,准备sleep,中断标志位为 "+isInterrupted());
					//线程在sleep时,如果我们调用interrupt(),会抛出InterruptedException异常
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					System.out.println(threadName+"捕获到中断异常时,子线程的中断标志位为 "+isInterrupted());
					//关键点,如果在异常中不调用interrupt方法,中断标志位一直是false,while循环一直继续
					//interrupt();
					e.printStackTrace();
				}
			}
			System.out.println(threadName+" 子线程跳出中断,中断标志位为"+isInterrupted());
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		Thread myThread = new MyThread();
		myThread.start();
		Thread.sleep(800);
		myThread.interrupt();
	}
}

此时如果我们不在catch块中调用interrupt()

当myThread.interrupt();时

子线程会捕获异常,但同时中断标志位会被复位成false

然后满足while(!isInterrupted()) ,继续下一个循环

所以必须在捕获异常时,再次调用interrupt(),确保中断标志位为true

结果如下

不在catch块中调用interrupt(),当捕获异常后子线程扔在继续运行

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

如果我的文章对您有点帮助,麻烦点个赞,您的鼓励将是我继续写作的动力

如果哪里有不正确的地方,欢迎指正

如果哪里表述不清,欢迎留言讨论

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值