中断线程 interrupt

调用interrupt(),通知线程应该中断:

1 如果线程处于阻塞状态,则线程立即退出被阻塞状态,并抛出一个InterruptedException异常;

2 如果线程处于正常活动状态,那

package com.mall.controllor.alene;

import sun.management.snmp.jvminstr.JvmThreadInstanceEntryImpl;

/**
 * Created by 60341 on 2020/3/18.
 */
public class InterruptDemo {
    /*
    interrupt() 其作用是中断此线程(此线程不一定是当前线程,而是指调用该方法的Thread实例所代表的线程),但实际上只是给线程设置一个中断标志,线程仍会继续运行。
     */
    public static void main(String[] args) throws InterruptedException {
        Runnable interruptTask = new Runnable() {
            @Override
            public void run() {
                int i = 0;
                try {
                    //在正常运行任务时,经常检查本线程的中断标志位,如果被设置了中断标志就自行停止线程
                    while(!Thread.currentThread().isInterrupted()){
                        Thread.sleep(100);
                        i++;
                        System.out.println("CurrentThread name is " + Thread.currentThread().getName() + ";CurrentThread status is " + Thread.currentThread().getState() + " loop "+ i);
                    }
                } catch (InterruptedException e) {
                    //在调用阻塞方法时,正确处理InterruptedException异常,在catch异常后就结束线程。
                    System.out.println("CurrentThread name is " + Thread.currentThread().getName() + ";CurrentThread status is " + Thread.currentThread().getState()+ " catch InterruptedException");
                }
            }
        };
        Thread t1 = new Thread(interruptTask,"t1");
        System.out.println(t1.getName()+" "+ t1.getState() + " is new");

        t1.start();
        System.out.println(t1.getName()+" "+ t1.getState() + " is started");

        //主线程休眠300ms,主线程给t1发中断指令;
        Thread.sleep(300);
        //t1线程收到中断命令,isInterrupted()置为false,while(!Thread.currentThread().isInterrupted())立刻被检测到,如果在阻塞状态,则抛出异常被catch处理。如果是正常运行,只将阻塞标志置为true,线程继续进行,不影响下面操作。
        t1.interrupt();
        System.out.println(t1.getName()+" "+ t1.getState() + " is interrupted");

        //主线程休眠300ms,查看t1状态;
        Thread.sleep(300);
        System.out.println(t1.getName()+" "+ t1.getState() + " is interrupted now");
    }
    /*输出:
    t1 NEW is new
    t1 RUNNABLE is started
    CurrentThread name is t1;CurrentThread status is RUNNABLE loop 1
    CurrentThread name is t1;CurrentThread status is RUNNABLE loop 2
    t1 TIMED_WAITING is interrupted
    CurrentThread name is t1;CurrentThread status is RUNNABLEcatch InterruptedException
    t1 TERMINATED is interrupted now
     */
}

么该线程的中断标志设为true,被设置中断标志的线程将继续正常运行,不受影响。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值