Your lungs don’t know anything. They’re just designed to take advantage of chemistry/physics.
When your CO2-laden, oxygen poor blood arrives at your lungs full of relatively oxygen-rich air the concentration of gasses starts to balance out. That is, CO2 flows out of your blood into your lungs and oxygen flows from your lungs into your blood. This is just basic physics. If I have a tank full of CO2 and a tank full of oxygen and connect them, the concentration of each gas in the connected system will approach an equilibrium.
However, your body also tips the scales of this process to go further than it otherwise would. Hemoglobin, the protein that bonds to CO2 and O2 to ferry it around your body, has a greater affinity for bonding with O2. If CO2 and O2 are around some hemoglobin in similar concentrations, the hemoglobin will bond with the oxygen. This means that, as oxygen flows into your blood it gets sucked up and carried away by red blood cells. This means the concentration of oxygen in blood at the lung-bloodstream interface remains low. Oxygen keeps flowing from your lungs into your blood.
Latest Answers