[英]How to execute only one thread and receive a Future without creating an ExecutorService?
I need to execute only aa single thread with the ability to cancel it. 我只需要执行一个可以取消它的线程即可。 I found that I can achieve this using
Future<T>
s. 我发现可以使用
Future<T>
实现此目的。 Right now I use it like this: 现在,我像这样使用它:
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<Void> future = executorService.submit(copyCallable);
executorService.shutdown();
Since ExecutorService
s are usually used to manage a multiple threads, I was wondering if there was a more efficient way to achieve this without creating one. 由于
ExecutorService
通常用于管理多个线程,因此我想知道是否存在一种更有效的方法来创建一个线程。 Thanks. 谢谢。
Interryprion is implemented by both Thread and calling method. Interryprion由Thread和调用方法实现。 Your thread need to listen for InterruptedException or check interruption flag at convenient points in time.
您的线程需要在方便的时间点监听InterruptedException或检查中断标志。 Calling code should call t.interrupt() for notifying Thread that it should stop.
调用代码应该调用t.interrupt()来通知Thread它应该停止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.