I want to create a background Thread handling some tasks (Runnable) and executing them in the order in which they are posted.
Important : these tasks must NOT be executed on the Event Dispatcher Thread.
Something like :
BackgroundEventThread backgroundEventThread = new BackgroundEventThread();
then, later, and in many places in the code:
Runnable thingToDo = new Runnable(){...};
backgroundEventThread.executeThis(thingToDo);
//the things to do will be executed in the order in which they are posted.
The class BackgroundEventThread
should be quite straightforward to code, but I was wondering if such a class already existed in some place unknown to me in the JDK or in some common library...
EDIT : I don't know in advance the number of tasks to execute on this thread.
I could have:
And I need task2 (that I don't know in advance) to be executed after task1, and I want all these tasks to be executed asap.
Exactly like tasks posted on the EDT, but NOT on the EDT.
Sounds like a job for java.util.concurrent.ThreadPoolExecutor.
You can set this up with a "pool" of a single thread, and then throw tasks at it to execute for you.
Check SwingWorker
An abstract class to perform lengthy GUI-interacting tasks in a dedicated thread.
All the necessary details as of how to use it are in the javadoc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With