JAVA多线程——线程的中断

JAVA中的线程中断

1.Thread.interrupt()  —— 设置interrupted为true

源码:
public void interrupt() {
        if (this != Thread.currentThread())
            checkAccess();

        synchronized (blockerLock) {
            Interruptible b = blocker;
            if (b != null) {
                interrupt0();           // Just to set the interrupt flag
                b.interrupt(this);
                return;
            }
        }
        interrupt0();
    }

只有线程自身可以中断自身的运行,不然checkAccess()就会抛出SecurityException
java使用一个中断位来标记一个线程是否已经中断,中断位的作用就是提醒程序员线程达到了中断的条件
在调用wait()系列、sleep()系列、join()系列方法后中断位会被清除,但是并不会中断线程
当前线程会收到InterruptedException,可以做出一些处理(退出线程等)

2.t.isInterrupted()

源码:
public boolean isInterrupted() {
        return isInterrupted(false);
    }

检测线程t是否已经进入中断状态,自己检测自己

3.Thread.interrupted()
源码:
    public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }
检测某个线程是否已经进入中断状态,由其他线程代劳,但是会清除中断位
意味着如果调用该方法两次,第二次返回的结果将为false
第一次:false -> true , 第二次: true -> false

线程中断测试:
<pre style="font-family: 宋体; font-size: 10.5pt; background-color: rgb(255, 255, 255);"><pre name="code" class="java">public class TestInterruptException implements Runnable {

    public static void main(String[] args) {
        Thread t = new Thread(new TestInterruptException());
        t.start();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //中断该线程实例
        t.interrupt();
    }

    @Override
    public void run() {
        //while(true)也要在try-catch块里面
        int number = 0;
        try {
            while (true) {
                checkNum(number);
                number++;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println(Thread.currentThread().getName() + " is interrupted");
        }
    }

    private void checkNum(int number) throws InterruptedException {
        if (number % 50000000 == 3) {
            System.out.print(number);
        }
        //检测当前线程是否已经中断了
        if (Thread.interrupted()) {
            //发出通知线程已经处于中断状态
            throw new InterruptedException();
        }
    }
}


 
 
 
 









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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值