如何停止通过实现runnable接口创建的线程? [英] How to stop a thread created by implementing runnable interface?

查看:443
本文介绍了如何停止通过实现runnable接口创建的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过实现runnable接口创建了类,然后在我的项目的其他一些类中创建了许多线程(接近10个)。
如何阻止其中一些线程?

I have created class by implementing runnable interface and then created many threads(nearly 10) in some other class of my project.
How to stop some of those threads?

推荐答案

最简单的方式是 interrupt()它,这会导致 Thread.currentThread()。isInterrupted()返回 true ,也可能抛出 InterruptedException 在线程等待的某些情况下,例如 Thread.sleep() otherThread .join() object.wait()等。

The simplest way is to interrupt() it, which will cause Thread.currentThread().isInterrupted() to return true, and may also throw an InterruptedException under certain circumstances where the Thread is waiting, for example Thread.sleep(), otherThread.join(), object.wait() etc.

run()您需要捕获该异常的方法和/或定期检查 Thread.currentThread()。isInterrupted()值和做某事(例如,突破)。

Inside the run() method you would need catch that exception and/or regularly check the Thread.currentThread().isInterrupted() value and do something (for example, break out).

注意:虽然 Thread.interrupted()似乎是与 isInterrupted()相同,它有一个令人讨厌的副作用:调用中断() 清除 中断的标志,而调用 isInterrupted()没有。

Note: Although Thread.interrupted() seems the same as isInterrupted(), it has a nasty side effect: Calling interrupted() clears the interrupted flag, whereas calling isInterrupted() does not.

其他非中断方法涉及使用stop( volatile )标记正在运行的线程监视器。

Other non-interrupting methods involve the use of "stop" (volatile) flags that the running Thread monitors.

这篇关于如何停止通过实现runnable接口创建的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆