源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

java通过共享变量结束run停止线程的方法示例

  • 时间:2022-12-29 00:06 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:java通过共享变量结束run停止线程的方法示例
stop()方法已经被弃用,原因是不太安全。API文档中给出了具体的详细解释。 通过interrupted()方法打断线程。不推荐。 通过共享变量结束run()方法,进而停止线程。如实例
[u]复制代码[/u] 代码如下:
public class ThreadInterrupt {     public static void main(String []args){         Runner run = new Runner();         run.start();         try {             Thread.sleep(10000);         } catch (InterruptedException e) {             // TODO Auto-generated catch block         }         //run.stop();//已经废弃的方法,不建议使用,过于粗暴         //run.interrupt(); //抛出异常,但是在异常处理中写业务显然不合适,不建议使用         run.flag=false;//建议使用的停止线程的方法     } } class  Runner extends Thread{     boolean flag = true;     public void run(){     /*    while(true){             System.out.println(new Date()+"----");             try {                 sleep(1000);             } catch (InterruptedException e) {                 // TODO Auto-generated catch block                 System.out.println("Interrupted");                 return;             }         }         */         while(flag){             System.out.println(new Date()+"----");             try {                 sleep(1000);             } catch (InterruptedException e) {                 // TODO Auto-generated catch block                 System.out.println("Interrupted");                 return;             }         }     } }
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部