Formation of lactic acid in muscles occurs when insufficient oxygen is supplied to the muscles, resulting in the release of energy via anaerobic cellular respiration instead of by aerobic cellular respiration.
Muscles need energy in order to contract. They receive energy when chemical energy is released from certain molecules, e.g. glucose (a type of sugar), that were previously consumed in food. Most of the chemical energy (i.e. the energy released when certain chemical bonds are broken during chemical reactions) is released to muscles when glucose and oxygen react together in a process called aerobic respiration.