Preventing Unwanted Thoughts

How can one prevent unwanted thoughts from springing in the mind automatically?