'Why is this foreground block executed before the background block if it's written later in the code?

#!/bin/bash

{ echo "1" ;
  sleep 3 ;
  echo "2"
} &
{ echo "a"
  sleep 1
  echo "b"
}

The output is

a
1
b
2

Why? Shouldn't echo "1" be executed immediately? Why the output is not

1
a
b
2


Solution 1:[1]

I would say, it could be both outputs. And even any output with only constraints being that a is before 1 and b is before 2:

a 1 b 2, b 2 a 1, a b 1 2, a b 2 1, b a 1 2, b a 2 1.

However, it is likely b could be output before a, because the echo b is evaluated by the script's shell, not by a forked/cloned sub-shell...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1