0
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.

2
  • 2
    if running one single thread, call cat1, cat2, cat2 sequentially; if in multiple thread environment, you need some thread synchronization knowledge, e.g. wait, notify, join, etc. Commented Dec 24, 2023 at 8:24
  • Some thoughts: If same kind of objects need to run sequentially, there is no need for threads, is there? Alternatively, if you want parallel execution of some workloads you can use a queue. Take care that, when workloads should be executed sequentially, the first queues the second, the second queues the third and so on. Finally, if you have no control in the order they are queued, you may want to lock in some way and coordinate the locks between the workloads, but this is not only inefficient, it is also dangerous for deadlocks. Commented Dec 24, 2023 at 8:27

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.