How to queue threads in java

84 views Asked by At
public void meow(){
        synchronized (Cat.class) {
        sout("meow");
            }
 }

Let's say program has cat1 cat2 cat3 objects.

If cat1 wants to run the meow function first, let cat1 run it first,
if cat2 wants it to run second, cat2 should run it and then cat3 last.
FIFO logic.

However, I think jvm normally sets this itself, so I cannot prioritize it according to the request order. How can I do this in java?

I need an easy way.

1

There are 1 answers

0
Basil Bourque On

Single-threaded executor service

If you have tasks you want to run in sequential order, submit them to an executor service backed by a single thread.

try (
    ExecutorService executorService = Executors.newSingleThreadExecutor() ;
) {
    … do some work
    executorService.submit( someRunnable ) ;
    … do some work
    executorService.submit( someOtherRunnable ) ;
    … do some work
    executorService.submit( anotherRunnable ) ;
}
// Flow blocks here if any tasks not yet done. 

Waiting for series of tasks

Of course, if your original thread has no other work to perform, if the original thread is merely waiting for the submitted tasks to complete, then there is no point to using another thread. Skip the executor service, just run your tasks directly in the original thread.