sequential event processing via executorservice
I have an event queue to process. A thread adds events to the queue.
I have created a runnable Task that in therun
method does all which is necessary to process the event.
I have declared an Executors.newCachedThreadPool();
and I execute
each Task.
public class EventHandler {
private sta开发者_StackOverflow社区tic final ExecutorService handlers = Executors.newCachedThreadPool();
public void handleNextEvent(AnEvent event){
handlers.execute(new Task(evt));
}
public class Task implements Runnable{
@Override
public void run() {
//Event processing
}
}
public AnotherClass{
public void passEvent(AnEvent evt)//This is called by another thread
{
EventHandler.handleNextEvent(evt);
}
}
My problem is that if I call execute
of the executor, my code will get the next event and run next runnable via the executor.
My purpose is to process next event from queue only after previous task has ended.
Thanks
Executors.newCachedThreadPool()
will create new threads on demand, so it's not what you want. You want something like Executors.newSingleThreadExecutor()
, which will process the events one at a time, and queue up the rest.
See javadoc:
Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time.
I think Executors.newSingleThreadExecutor()
and the submit()
Method are the solution to your problem: http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorService.html
精彩评论