线程常用的两个有效停止的方法

本文探讨了Java中处理线程中断的两种方法:return法和异常法。通过具体代码示例,详细介绍了如何在Mythread类的run方法中检查线程是否被中断,并采取相应措施结束线程运行。

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

建议使用异常法,catch中可以将异常向上抛出,使得线程停止的事件可以传播

1.return 法

public class Mythread extends Thread{
      public void run(){
           while(true){
               if(this.isInterrupted()){
                    //TO-DO ; 
                    return;
                }
                //TO-DO;
           }
      }
}

public class returnMain{
     public static void main(String[] args) throws InterruptException{
           Mythread mt = new Mythread();
           mt.start();
           Thread.sleep(1000);
           mt.interrput();
      }
}

2.异常法

public class Mythread extends Thread{
      public void run(){
         try{
           while(true){
               if(this.isInterrupted()){
                    //TO-DO; 
                    throw new InterruptException();
                }
                //TO-DO;
           }
         }catch(InterruptException e){
            //TO-DO;
         }
      }
}

public class returnMain{
     public static void main(String[] args) throws InterruptException{
           Mythread mt = new Mythread();
           mt.start();
           Thread.sleep(1000);
           mt.interrput();
      }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值