JAVA多线程编程之判断终止状态Interrupted和isInterrupted的区别

本文介绍了Java中线程中断的概念及使用方法,包括interrupted()和isInterrupted()的区别,并通过示例代码演示了如何判断线程是否被中断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一基本概念:

    1.Interrupted   是判断调用这行代码的线程是否中断,,重复调用这个方法会清除中断状态,换句话说连续调用2次该方法即使第一次返回true【中断】第二次也会返回false。

    2.this.isInterrupted它是测试线程是否已经中断,测试Thread对象是否中断状态,但不清除状态标识。

二代码示例:

   示例一

   自定义线程类:

   public class MyThread extends Thread{

              @Override

              public void run(){

                      super.run();

                      for (int i=0;i<500000;i++){

                             System.out.println("i="+(i+1));

                      }

              }

  }

   运行类Run.java

   public class run{

         public static void main(String[ ] args){

               try{

                     MyThread thread=new MyThread();

                     thread.start();

                     Thread.sleep(1000);

                     thread.interrupt();

                     System.out.println("是否中断1?="+thread.interrupted());

                     System.out.println("是否中断1?="+thread.interrupted());

               }catch(InterruptedException e){

                     System.out prinln("main catch");

                      e.printStackTrace();

               }

                     System.out prinln("end!");

        }

  }

  运行结果为:

       

       证明:interrupted()是判断main线程是否中断,它是main线程调用的方法;

    示例二:     

     Run2.java

     public class run2{

         public static void main(String[ ] args){

                 Thread.currentThread.interrupt(); //中断线程

                  System.out.println("是否中断1?="+Thread.interrupted());

                  System.out.println("是否中断1?="+Thread.interrupted());

                  System.out prinln("end!");

         }

    }

    运行结果:

       

   证明:interrupted()连续连词调用  第二次为flase   每次调用清除中断状态。

    示例三:   Run3.java

    public class run3{

         public static void main(String[ ] args){

               try{

                     MyThread thread=new MyThread();

                     thread.start();

                     Thread.sleep(1000);

                     thread.interrupt();

                     System.out.println("是否中断1?="+thread.isInterrupted());

                     System.out.println("是否中断1?="+thread.isInterrupted());

               }catch(InterruptedException e){

                     System.out prinln("main catch");

                      e.printStackTrace();

               }

                     System.out prinln("end!");

        }

  }

     运行结果为:

   

     证明:isInterrupted测试Thread对象是否已经中断状态,但不清除中断标志。

    

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值