Java:手动停止线程的几种方式 |
您所在的位置:网站首页 › java线程停止执行 › Java:手动停止线程的几种方式 |
记录……
1、业务逻辑实现,借助AtomicBoolean等相关api做标识符 2、stop()方法,但此方法过于粗暴,可能会导致安全问题 3、interrupt()方法,推荐 ①、线程内部 @Override public void run() { while (true){ if(Thread.currentThread().isInterrupted()){ log.info("退出当前线程:{}", Thread.currentThread().getName()); break; } log.info("业务逻辑……"); } }②、主线程或业务代码中 Thread thread = new Thread(); if(!thread.isInterrupted()){ try { thread.interrupt(); }catch (Exception e){ log.error("线程停止失败:{},线程:{}", e.getMessage(), thread.getName()); } }
需要注意的是: interrupt()并不会直接停止线程,而是告诉线程希望停止执行。 因此在线程内容执行体中,使用Thread.currentThread().isInterrupted()判断interrupt并做出相应处理 即interrupt()和Thread.currentThread().isInterrupted()组合使用
相关文档:https://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html
完
|
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |