This is self-defense 101, kids. Learn how and when to overcome the social expectation to be friendly with everyone. Predators rely on that conditioning.
This also works when you're in the gym working out, or doing homework in a coffee shop: any time when you're obviously engrossed in something yet someone feels you only showed up for their entertainment.
First of all, don't ignore anyone who is obviously trying to get your attention. Don't let it get to that point. If anyone moves within 3-4 feet of you, glance up. Be aware of your surroundings. Don't make eye contact, just note who is nearby, how they are dressed, what they are carrying. Cultivate an expression of alert concentration. Be alert. Be in control of your environment.
If someone moves into your personal space and stands or walks alongside you, notice them. Don't smile. Give them a rake of your eyes that says, "I see you." Go back to what you were doing.
This will usually discourage them better than pretending they aren't there, because you will have already signaled your disinterest.
If it doesn't, if the entitled fuckwhistle waves his hand in front of your face or does something else to demand your attention, look up with an expression of weary disdain, remove one headphone, raise an eyebrow. Don't smile.
Repeat: don't smile (unless of course you actually WANT to talk to this person). Take in their face and height with an expression of alert indifference, as if reading the menu board at McDonald's. Note hair and eye color, and distinguishing features.
Make him speak first. He may genuinely need information like directions or the date and year, if he's a time traveler. But if you're in a crowded place and he chose to interrupt the girl with the headphones on, odds are he's just being an entitled fuckwhistle.
As soon as he tries any conversational gambit, i.e. "Are you a student? What are you reading? What's good on the menu? Your hair is so pretty," your response is as follows:
"I'm not actually here for conversation, thanks."
Repeat if necessary. Be polite but cool. Do not follow his conversational script. Look at him until he goes away.
Put your ear bud back in. Go back to what you were doing. Maintain awareness of your surroundings.