I have a demo Spring boot project, and will create a Thread Pool when starts application.
In Main Thread, if there are:
Task A
: with lots of API call, and will be submitted to Thread PoolTask B
: only a database query, and will not be submitted to Thread Pool
I have below questions:
- Will
Task B
execute early thenTask A
if following below code approach? - Can
Task B
wait untilTask A
have finished and then execute? If can, how to achieve? - Assume if there are no idle Worker Threads to handle
Task A
, what will happen ? Will the Main Thread skipTask A
and continue to executeTask 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.