「美好,一直在身边」震惊!这样终止线程,竟然会导致服务宕机?( 三 )
* exceptions does not print out a message or otherwise notify the * application if the uncaught exception is an instance of * ThreadDeath. * * @exception SecurityException if the current thread cannot * modify this thread. * @see #interrupt * @see #checkAccess * @see #run * @see #start * @see ThreadDeath * @see ThreadGroup#uncaughtException(Thread,Throwable) * @see SecurityManager#checkAccess(Thread) * @see SecurityManager#checkPermission * @deprecated This method is inherently unsafe. Stopping a thread with * Thread.stop causes it to unlock all of the monitors that it * has locked (as a natural consequence of the unchecked * ThreadDeath exception propagating up the stack). If * any of the objects previously protected by these monitors were in * an inconsistent state, the damaged objects become visible to * other threads, potentially resulting in arbitrary behavior. Many * uses of stop should be replaced by code that simply * modifies some variable to indicate that the target thread should * stop running. The target thread should check this variable * regularly, and return from its run method in an orderly fashion * if the variable indicates that it is to stop running. If the * target thread waits for long periods (on a condition variable, * for example), the interrupt method should be used to * interrupt the wait. * For more information, see * Why * are Thread.stop, Thread.suspend and Thread.resume Deprecated?. */@Deprecatedpublic final void stop { SecurityManager security = System.getSecurityManager; if (security != ) { checkAccess; if (this != Thread.currentThread) { security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION); } } // A zero status value corresponds to "NEW", it can't change to // not-NEW because we hold the lock. if (threadStatus != 0) { resume; // Wake up thread if it was suspended; no-op otherwise } // The VM can handle all thread states stop0(new ThreadDeath);} 可以看出 stop 方法被 @Deprecated 注释修饰了 , 而被此注解修饰的代码表示为过时方法 , 不建议被使用 。 从 stop 的备注信息可以看出 , 官方也不建议使用 stop, 说它是一个非安全的方法 。
本文插图
正确终止线程 那如何终止线程呢?这里提供 2 个正确的方法:
- 设置退出标识退出线程;
- 使用 interrupt 方法终止线程 。
推荐阅读
- @选择一款5G手机,回到美好生活,天猫“418”大促正是个好时机!
- 【美好,一直在身边】加快工业互联网与制造业融合,遂宁开启工业互联网时代→
- 『美好,一直在身边』新能源新项目!长虹控股投资近20亿元锂电池项目在绵阳开工
- 美好,一直在身边@微信小程序增加跨境电商服务类目
- 「美好,一直在身边」马鞍形 星空顶 杭州地铁5号线的这个入口很特别
- 美好,一直在身边@电子城转向新型科技服务业务显成效 科技服务收入占比持续增加
- 美好,一直在身边■购物社交平台首推“人品评级”,未来已来
- 『美好,一直在身边』37家公司市值超百亿,科创板造富效应显著,会一直火下去么?
- 『Google Play』一直说的订阅政策更新来了 6月16日是最后期限
- 美好,一直在身边■2020年第12批CDN牌照下发:全国CDN经营资质企业突破200家
