Reputation: 15821
The task is as follows.
There is a queue of tasks. It is necessary to create a thread that periodically these problems will come.
comes to mind is the following mechanism. Create a class that inherits from Thread and a run method to do something like this:
while (! isInterrupted ()) {
while (executedTask! = null) {
// Execute task
// Push callback about successfully processed task
executedTask == null;
}
}
But looking at the code, intuition suggests that someone is me "hands behind such whacks" :)
Therefore, I want to ask how would be better to implement this task. It is no code, just words. I would be grateful for links to examples.
------------------ -------------------
| 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 |
|----------------------->|
. . .
Upvotes: 1
Views: 82
Reputation: 13570
You should create an ExecutorService with only one thread like.
ExecutorService executor = Executors.newFixedThreadPool(1);
And then when you want to add a task to the queue create a new runnable and submit it.
executor.submit(new Runnable() {
public void run() {
//your code here
}
});
A single threaded ExecutorService will only run one task at a time and will queue up new tasks that you submit to it and run them in the order you submit them.
As a bonus this pattern can be particularly useful if you have a multi threaded environment and want to avoid complex synchronization and locking issues.
Upvotes: 1