线程中断的理解

线程终止的条件:run方法运行结束或有没有捕获的异常出现。
在java 的早期阶段我们知道有一个stop方法,其他线程可以调用它来终止线程,但是这个方法已经被弃用了。interrupt方法可以中断调用它的线程。当一个线程调用interrupt时,线程的标识位就会被改为true,线程会不断检测这个标识位是不是被中断过,以判断线程是否应该被中断。
想知道这个线程是否被中断,可以调用Thread.currentThread().isInterrupted()方法看

while(Thread.currentThread.isInterrupted()){
// you can do whatever you want to do
}

还可以调用Thread.currentThread.interrupted()将标示位进行复位。但是当一个线程被阻塞,就无法判断是否中断状态。如果一个线程处于阻塞的状态,线程在检查中断标识位时是true,就会抛出中断异常,在抛出异常前时会将中断的标识位复原。注意:中断不代表终止,中断线程就是为了引起线程注意,中断的可以自己决定如何处理中断请求,不要在抓捕中断异常后不作处理。

处理的两种方式:
1try {
Thread.sleep(50);
}catch(){
// 将当前的线程中断的标示位复原
Thread.currentThread.interrupted();
}
2void task()throws InterceptionException{
Thread.sleep(10);
}
利用中断安全的终止线程
public class StopThread{
	public static void main(String[]args)throws InterruptedException{
	TestThread test = new TestThread();
	Thread thread = new Thread(test);
	thread.start();
	TimeUtil.SECONDS.sleep(1000);
	thread.interrupt();		//当被调用的时候,thread的中断标识位立马就是true
	}
	public class TestThread implements Runable{
	@overide
	public void run(){
	while(!Thread.currentThread.isInterrupted()){	//判断是不是处于中断的状态
		System.out.print("我还没有被阻塞!!!!,哈哈哈哈");
	}
	System.out.print("我被阻塞了,他么的");
	 //  thread.currentThread.interrupted();可以将中断标识位进行复位false    
	     }
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值