你不知道的interrupt、interrupted、isInterrupted


被调用的方式:
interrupt和isInterrupted 是Thread类普通方法,被实例对象调用,都是非静态方法,也可以用线程对象来访问,例如t.interrupt(),t.isInterrupted()。
interrupted是Thread类中的静态方法,可以通过类名形式来访问:Thread.interrupted()

概念区分:(注意留意this和current)
interrupt()方法:中断此线程(原文:Interrupts this thread)(此线程不一定是当前线程,而是指调用该方法的Thread实例所代表的线程)
interrupted()方法:测试当前线程是否被中断(检查中断标志)原文:Tests whether the current thread has been interrupted,返回一个boolean并清除中断状态,第二次再调用时中断状态已经被清除,将返回一个false。
isInterrupted()方法:测试此线程是否被中断 ,不清除中断状态(原文:Tests whether this thread has been interrupted)

实践练习:
1、interrupt()不能中断正在运行中的线程,只能改变中断状态。
public class InterruptionTestForJava implements Runnable{
  
    public static void main(String[] args) throws InterruptedException {
        Thread testThread = new Thread(new InterruptionTestForJava(), "InterruptionInJava");
        testThread.start();
        Thread.sleep(1000);
        //interrupt()不能中断在运行中的线程,它只能改变中断状态而已。
        testThread.interrupt();
        System.out.println("main end");

    }
    @Override
    public void run() {
        while (true){
            if (Thread.currentThread().isInterrupted()){
                System.out.println("yes ,i am interrupted,but i am still running");
            }else {
                System.out.println("not yet interrupted");
            }
        }
    }
运行main方法发现程序没有结束,在打印完“not yet interrupted”后,继续疯狂打印“yes ,i am interrupted,but i am still running”
2、那么如何正确的中断?一种处理方式是在中断状态被修改后,直接返回return
public class InterruptionTestForJava implements Runnable{
  
    public static void main(String[] args) throws InterruptedException {
        Thread testThread = new Thread(new InterruptionTestForJava(), "InterruptionInJava");
        testThread.start();
        Thread.sleep(1000);
        //interrupt()不能中断在运行中的线程,它只能改变中断状态而已。
        testThread.interrupt();
        System.out.println("main end");

    }
    @Override
    public void run() {
        while (true){
            if (Thread.currentThread().isInterrupted()){
                System.out.println("yes ,i am interrupted,but i am still running");
                return;
            }else {
                System.out.println("not yet interrupted");
            }
        }
    }
输出如下:
not yet interrupted
……
not yet interrupted
not yet interrupted
not yet interrupted
not yet interrupted
main end
yes ,i am interrupted,but i am still running
3、“优雅”的处理方式——无阻塞情况(无sleep、wait、join方法调用)
public class InterruptionTestForJava implements Runnable{
    //如何中断线程?通过添加一个开关来做到
    private static volatile  boolean on = false;
    public static void main(String[] args) throws InterruptedException {
        Thread testThread = new Thread(new InterruptionTestForJava(), "InterruptionInJava");
        testThread.start();
        Thread.sleep(1000);
        //interrupt()不能中断在运行中的线程,它只能改变中断状态而已。
        testThread.interrupt();
        InterruptionTestForJava.on = true;
        System.out.println("main end");

    }
    //无线程阻塞的情况下可以通过一个开关
    @Override
    public void run() {
        while (!on){
            if (Thread.currentThread().isInterrupted()){
                System.out.println("yes ,i am interrupted,but i am still running");
                return;
            }else {
                System.out.println("not yet interrupted");
            }
        }
    }
}
4、“优雅”的处理方式——有阻塞情况
public class InterruptionTestForJava implements Runnable{
    //有线程阻塞情况时如何中断线程?考虑通过一个开关来实现
    private static volatile  boolean on = false;
    public static void main(String[] args) throws InterruptedException {
        Thread testThread = new Thread(new InterruptionTestForJava(), "InterruptionInJava");
        testThread.start();
        Thread.sleep(1000);
        //interrupt()不能中断在运行中的线程,它只能改变中断状态而已。
        InterruptionTestForJava.on = true;
        testThread.interrupt();
        System.out.println("main end");

    }

    //如果有线程阻塞情况就无法通过开关变量来处理,通过interrupt函数可以迅速中断被阻塞的线程,抛出一个InterruptedException,将线程从阻塞状态解救出来
    @Override
    public void run() {
        while (!on){
          try {
              Thread.sleep(100000);
          } catch (InterruptedException e) {
              System.out.println("Caught exception right now :" + e);
          }
        }
    }
}
感谢此篇文章:https://blog.csdn.net/zhuyong7/article/details/80852884
 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/418938.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

mysql 查询语句性能优化

https://www.cnblogs.com/jiligalaer/p/5609373.html https://blog.csdn.net/sunjiaminaini/article/details/77370962 https://blog.csdn.net/wangzhuo14/article/details/51771472

软件与软件工程的概念

第一章 软件与软件工程的概念 读书笔记:主要参考教材《软件工程概论》和PPT 软件的概念软件是计算机系统中与硬件相互依存的另一部分,它是包括程序,数据及其相关文档的完整集合。程序是按事先设计的功能和性能要求执行的指令序列。数据是使程…

Spring的@Transactional注解踩坑

Transactional介绍 Spring为开发人员提供了声明式事务的使用方式,即在方法上标记Transactional注解来开启事务。大家在日常的开发中很多业务代码对数据进行操作的时候一定是希望有事务控制的。 比如电商卖东西业务,代码的逻辑是商家先生成一个订单&…

java 23种设计模式

https://www.cnblogs.com/malihe/p/6891920.html https://www.runoob.com/design-pattern/factory-pattern.html https://www.cnblogs.com/JavaHxm/p/11016315.html

git多分支频繁切换导致IDEA工具maven工程项无法识别java文件的一种解决方法

由于频繁的进行git多分支的切换,导致本地maven工程依赖切换失败,进而导致项目无法识别java工具,多次rebuild项目均以失败而告终。 提供一种有效的正确方式: 在IDEA的terminal输入命令 mvn clean mvn install -Dmaven.test.skipt…

MySQL中去除字段中的回车符和换行符

https://blog.csdn.net/u012586848/article/details/50997865

简说SQLite

SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中。什么是ACID?指数据库事务正确执行的四个基本要素的缩写。包含:原子性(Atomicity)、一致性&#xff0…

MySQL中count(*)用法

count()函数:一个聚合函数,对于返回的结果集,一行行地判断,如果 count 函数的参数不是 NULL,累计值就加 1,否则不加。最后返回累计值 对不同count()统计函数…

Java “\”与\\的替换

Java replaceAll方法中,必须用“\\”表达一个"",因为Java中“\”是转义字符,通常会误以为“\”就能表示"",实际上,replaceAll算法的实现运用了正则表达式,所以这里经历了两次转化,即是replaceAll(…

PHP闭包(Closure)初探(转载 http://my.oschina.net/melonol/blog/126694?p=2#comments)

匿名函数 提到闭包就不得不想起匿名函数,也叫闭包函数(closures),貌似PHP闭包实现主要就是靠它。声明一个匿名函数是这样: ?123$func function() {}; //带结束符可以看到,匿名函数因为没有名字&#xff0…

bootstrap 学习网址

http://edu.jb51.net/bootstrap/bootstrap-tables.html

手把手教你--JAVA微信支付(H5支付)

http://www.pianshen.com/article/901316384/ https://blog.csdn.net/qq_16927377/article/details/80542682

寻找子串

中国电信2016年IT研发工程师笔试题 12 给定一个已经排好序的字符串数组,空字符串散布在该数组中,编写一个函数寻找一个 给定字符串的位置。 解法:循环搜索第一个字符,第一个匹配则进行统计个数,当匹配个数等于子串长度时,则可以输…

css教程

https://www.runoob.com/css/css-tutorial.html

当下大部分互联网创业公司为什么都愿意采用增量模型来做开发?

现在互联网正在飞速的发展,各种各样的互联网创业公司如雨后春笋般的涌现。而在互联网初创企业中广泛运用的增量模型无疑是大家关注的重中之重,本文主要谈谈我个人对增量模型在互联网创业公司得到推广原因的初步理解。 1.把目标软件拆分为实现其部分功能增…

beetl 取list下标的问题

[DEBUG] 11:44:23.194 org.beetl.ext.nutz.LogErrorHandler.processExcption(LogErrorHandler.java:32) - 属性访问出错 11:44:23:属性获取异常(ATTRIBUTE_INVALID):[] 位于21行 资源:/platform/wage/calculation/detail/edit.html 属性访问出错 18| 19| <%for(item in map[…

横竖屏切换时候Activity的生命周期的总结

1、新建一个Activity&#xff0c;并把各个生命周期打印出来 2、运行Activity&#xff0c;得到如下信息 onCreate--> onStart--> onResume--> 3、按crtlf12切换成横屏时 onSaveInstanceState--> onPause--> onStop--> onDestroy--> onCreate--> onStart…

bootstrp-table 获取checkbox选中行的数据id

https://blog.csdn.net/qq_20603425/article/details/84253782