java多线程interrupt,isInterrupted,interrupted实例演示

public void Thread.interrupt();    //中断线程,设置中断标志位
public void Thread.isInterrupted();    //判断是否被中断
public void Thread.interrupted();    //判断是否被中断,并清除当前中断状态

最近在研究多线程,开始并不是太清楚三者的区别,尤其后两者,仔细想了个小例子,例子如下

线程类:

public class MyThread extends Thread{

	@Override
	public void run() {
		boolean flag=false;
		boolean interrupted;
		//死循环等待线程中断
		while(true){
			if(flag==false){
				//当前线程状态如果为中断,赋给变量flag
				interrupted = Thread.interrupted();
				if(interrupted==true){
					System.out.println("MyThread 线程状态为"+interrupted);
				}
				flag=interrupted;
			}
			//如果线程中断,这里打印且复位中断标志位
			if(flag){
				System.out.println("MyThread 已经被中断");
				interrupted=Thread.interrupted();
				System.out.println("复原 MyThread中断状态位");
				flag=interrupted;
			}
		}
		
			
	}
	
}

Run类:

public class Run {

	@SuppressWarnings("static-access")
	public static void main(String[] args) {
		MyThread my=new MyThread();
		my.start();//开启子线程
		my.interrupt();//中断子线程
		try {
			Thread.sleep(2000);//主线程sleep 2秒,让子线程充分运行
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		//死循环,如果子线程中断状态为非中断,则中断子线程,然后打印
		while(true){
			if(!my.isInterrupted()){
				my.interrupt();
				System.out.println("main 线程查看MyThread线程状态为"+my.isInterrupted()+"------------------");
			}
		}
		
		
		
	}
}

这个例子很简单,主线程先去中断子线程,子线程检测到中断后再恢复,然后主线程一直去中断,子线程一直恢复。

这里了解了:

1:中断线程只是一个标识位,并非真正的中断线程不让其执行,如果真要让其中断不在运行自己去实现(异常法,sleep,wait,join,线程正在阻塞中调用中断,会使线程抛出异常从而使线程结束)。

2:中断标识位是可以被恢复的,并且可以多次进行。

3:interrupted()再次调用会恢复中断标识位为false(true表示线程中断).

4:对三者的作用与用法有个具体了解。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jackson陈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值