Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event thread in java

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:

  • task0 (really short) happening at t0
  • task1 (long to process...) happening at t0+1s
  • task2 (short) happening at t0+5s etc.
  • task3 (etc, etc...)

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.

like image 480
Laurent K Avatar asked Feb 28 '23 20:02

Laurent K


2 Answers

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.

like image 85
Carl Smotricz Avatar answered Mar 08 '23 03:03

Carl Smotricz


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.

like image 35
Bozho Avatar answered Mar 08 '23 03:03

Bozho