任务如下。
There is a queue of tasks. It is necessary to create a thread that periodically these problems will come.
我想到的是以下机制。创建一个继承自 Thread 的类和一个 run 方法来执行如下操作:
while (! isInterrupted ()) {
while (executedTask! = null) {
// Execute task
// Push callback about successfully processed task
executedTask == null;
}
}
但是看看代码,直觉表明有人是我“幕后黑手”:)
所以我想问一下如何更好地实现这个任务。它不是代码,只是文字。如果能提供示例链接,我将不胜感激。
------------------ -------------------
| TaskHolder | | WorkerThread |
------------------ -------------------
| |
task | execute |
------->|----------------------->|
task#2 | hard-time task worked
------->|queue task until current|
|task is processed |
task#3 | |
------->|queue task until current|
|task is processed |
task#4 | |
------->|queue task until current|
|task is processed |
task#5 | |
------->|queue task until current|
|task is processed |
task#6 | |
------->|queue task until current|
|task is processed |
| |
| |
| task finished
| return result |
|<-----------------------|
| |
|pop task#2 from queue |
| execute task#2 |
|----------------------->|
. . .
最佳答案
您应该创建一个只有一个线程的 ExecutorService。
ExecutorService executor = Executors.newFixedThreadPool(1);
然后,当您想要将任务添加到队列中时,创建一个新的可运行并提交它。
executor.submit(new Runnable() {
public void run() {
//your code here
}
});
单线程 ExecutorService 一次仅运行一个任务,并将您提交给它的新任务排队并按照您提交的顺序运行它们。
作为奖励,如果您拥有多线程环境并希望避免复杂的同步和锁定问题,此模式可能特别有用。
关于java - 如何组织一系列运行任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29440501/