From what i think i learned, the embryo is female until a hormone is released from the females body and it changes gender, but i know it cant be random, maybe the XY chromosomes are there and tell the body to release that hormone. Certain species of fish can change gender at will when a dominant male or female dies, i think this is kinda irrelevant though.
/www.dailymail.co.uk/sciencetech/article-2302865/Is-end-men-Expert-predicts-males-extinct--says-process-started.html