JAVA多线程之(Interrupt)

 interrupt,顾名思义,即中断的意思。单独调用interrupt方法可以使得处于阻塞状态的线程抛出一个异常, 也就说,它可以用来中断一个正处于阻塞状态的线程;另外,通过interrupt方法和isInterrupted()方法来停止正在运行的线程。具体参照实例:


 

package nc.com.thread.traditional.example;

/**
 * interrupt,顾名思义,即中断的意思。
 * 单独调用interrupt方法可以使得处于阻塞状态的线程抛出一个异常,
 * 也就说,它可以用来中断一个正处于阻塞状态的线程;另外,
 * 通过interrupt方法和isInterrupted()方法来停止正在运行的线程。
* @ClassName: TestInterrupt 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author A18ccms a18ccms_gmail_com 
* @date 2015-12-19 下午07:07:53 
*
 */
public class TestInterrupt {
     
    public static void main(String[] args) throws Exception  {
        TestInterrupt test = new TestInterrupt();
        
        中断处于阻塞的线程,同时会有异常
        MyBlockThread thread = test.new MyBlockThread();
        thread.start();
        try {
            Thread.currentThread().sleep(2000);
        } catch (InterruptedException e) {
             
        }
        thread.interrupt();
        //中断处于运行中的线程
        //从这里可以看出,通过interrupt方法可以中断处于阻塞状态的线程。那么能不能中断处于非阻塞状态的线程呢?
        //运行该程序会发现,while循环会一直运行直到变量i的值超出Integer.MAX_VALUE。所以说直接调用interrupt方法不能中断正在运行中的线程。
        //但是如果配合isInterrupted()能够中断正在运行的线程,因为调用interrupt方法相当于将中断标志位置为true,那么可以通过调用
        //isInterrupted()判断中断标志是否被置位来中断线程的执行。比如下面这段代码:
        MyRunningThread  r = test.new MyRunningThread();
        r.start();
        try {
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
             
        }
        if(r.isAlive()){
        	r.interrupt();
        }
    } 
     
    class MyBlockThread extends Thread{
        @Override
        public void run() {
            try {
                System.out.println("进入睡眠状态");
                Thread.currentThread().sleep(10000);
                System.out.println("睡眠完毕");
            } catch (InterruptedException e) {
            	//可以在线程处于阻塞状态下被中断时处理数据
                System.out.println("得到中断异常");
            }
            System.out.println("run方法执行完毕");
        }
    }
    class MyRunningThread extends Thread{
        @Override
        public void run() {
            try {
              while(true){
            	  System.out.println("MyRunningThread  running----------------状态");
            	  if(isInterrupted()){
            		  //在这里面接受处理线程终止命令,如数据备份持久化等
            		  System.out.println("MyRunningThread  正在终止正在运行的线程");
            	  }
              }
            } catch (Exception e) {
                System.out.println("MyRunningThread 得到中断异常");
            }
            System.out.println("MyRunningThread  run方法执行完毕");
        }
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值