简体   繁体   English

如何仅执行一个线程并接收Future而无需创建ExecutorService?

[英]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.

相关问题 如何在不使用ExecutorService的情况下获取Future <MyObject>? - How can I get a Future<MyObject> without using ExecutorService? ExecutorService可能在调用线程上执行? - ExecutorService might execute on calling thread? 从ExecutorService运行的只有一个线程newFixedThreadPool大小为5 - Only one thread running from ExecutorService newFixedThreadPool of size 5 java ExecutorService newSingleThreadExecutor 是否仅使用一个线程执行所有任务? - Is java ExecutorService newSingleThreadExecutor performs all the tasks using only one Thread? 等待 Java 8 中的任何未来,而不为每个未来创建线程 - Wait on any future in Java 8 without creating thread per future 如何通过ExecutorService和Future正常退出 - How to exit gracefully with ExecutorService and Future 可以在不破坏和重新创建线程的情况下,使用同一线程一个接一个地执行许多任务吗? - Can same thread be used to execute many tasks one by one without destroying and re-creating thread? 如何在不使用ExecutorService的情况下实现固定线程池 - How to achieve fixed thread pool without using ExecutorService 如何使用 executor.execute 和 future.get() 结束任务(使线程超时)(通过上升中断)而不阻塞主线程 - How to end a task(timeout a thread) (by rising interrupt) using executor.execute and future.get() without blocking the main thread ExecutorService.execute()不返回线程类型 - ExecutorService.execute() does not return the thread type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM