使用类的方法中断Runnable(Interrupting a Runnable with a method of the class)
如何编写实现
Runnable
接口(从ExecutorService
启动)的类的方法,该类会中断线程?我知道我可以使用
Future fut = es.submit(foo);
(其中es
是ExecutorService
,foo
是我的类的一个实例),然后调用fut.cancel(true);
从应用程序的主要功能内部,但我如何从类本身内部调用类似的东西?我想在我的Runnable类中有一个方法
public void stop() {…}
所以我可以从任何地方(包括从应用程序的主函数
foo.stop()
调用foo.stop()
,它就像我使用了Future.cancel
函数一样工作(如果线程正在等待获取,它必须引发ÌnterruptedException)一个信号量)。How can I write a method of a class implementing the
Runnable
interface (started from anExecutorService
) that would interrupt the thread?I know that I can use
Future fut = es.submit(foo);
(wherees
is theExecutorService
andfoo
is an instance of my class) and then callfut.cancel(true);
from inside the main function of the application, but how do I call something like that from inside the class itself?I would like to have in my Runnable class a method
public void stop() {…}
so that I can call
foo.stop()
from anywhere (including from the main function of the application) and it will work as if I had used theFuture.cancel
function (it has to raise ÌnterruptedException` if the thread is awaiting to acquire a Semaphore).
原文:https://stackoverflow.com/questions/18813852