Home > database >  Execution Order of Thread in Java Main Thread
Execution Order of Thread in Java Main Thread

Time:01-17

I have a demo Spring boot project, and will create a Thread Pool when starts application.

In Main Thread, if there are:

  1. Task A: with lots of API call, and will be submitted to Thread Pool
  2. Task B: only a database query, and will not be submitted to Thread Pool

I have below questions:

  1. Will Task B execute early then Task A if following below code approach?
  2. Can Task B wait until Task A have finished and then execute? If can, how to achieve?
  3. Assume if there are no idle Worker Threads to handle Task A, what will happen ? Will the Main Thread skip Task A and continue to execute Task B first?
public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);

        // Task A submitting to Thread Pool
        executor.submit(() -> 
           // process 1: fetch API
           // process 2: call Database 
           // process 3: fetch API
           // process 4: call Database 
        );

        // Task B not submitting to Thread Pool
        db.query(xxx);

}

CodePudding user response:

It is not important if any of the tasks return anything. When things run in parallel threads then they run in parallel until one of them finished or you explicitly wait for one in the other.

What does run in parallel actually mean? Depends. If the machine where code runs on has multiple CPU cores available then it can actually run in parallel (one core handles one thread), if not then it may run in any random way. Something like "do one atomic operation in thread A, then two in thread B and then again one in thread A" may be one option, but it's nothing you can control. If you wan't to make sure things run in some certain order then either use Future.get(), Thread.join() or Javas completable future framework.

  • Related