如何在java中停止一个线程并让同一个线程做另一件事? [英] How to stop a thread in java and let the same thread to do another thing?
本文介绍了如何在java中停止一个线程并让同一个线程做另一件事?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我启动一个线程从互联网下载内容,有一次,该线程正在下载一个文件,然后我希望它停止并开始下载另一个文件,我该怎么办?我应该指望java中的并发机制吗?
I start one thread to download contents from the internet, at one time, the thread is downloading one file, and then i want it stop and begin to download another file, what should i do? should i count on the concurrency mechanism in java?
推荐答案
您可以使用 单线程执行器,然后当你杀死它(我希望优雅地)并启动一个新的时,它将确保它使用同一个线程.
You can start your thread using a single-thread executor, then when you kill it (gracefully I hope) and start a new one it will ensure that it's using the same thread.
// Suppose you have a DownloadFile class that implements Runnable
DownloadFile task1 = new DownloadFile();
...
ExecutorService exec = Executors.newSingleThreadExecutor();
Future<Boolean> future = exec.submit( task1, Boolean.TRUE );
...
// Cancel the task
future.cancel();
// Give the executor another task
DownloadFile task2 = new DownloadFile();
...
exec.submit( task2, Boolean.TRUE );
其他有用的文档:
这篇关于如何在java中停止一个线程并让同一个线程做另一件事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文