The Buddha described a method of controlling distracting and unwholesome thoughts in the discourse, Vitakkasanthana Sutta:
Essentially, we need to try, a step at a time, the following when confronting an unwholesome thought within:
1.Think of a good thing. In this case, the easiest is to think that not doing this bad thing is good in itself.
If the above attempt fails, and the unwholesome thoughts come up again, go to number 2:
2.Think of the bad repercussions this thought will bring; most of the time, these repercussions will be upon yourself (the law of karma).
If No. 2 is still not working, go to No. 3 and so-fourth:
3.Don’t think about it. (Find something else to do).
4.“Relax” distracting thought formations: As soon as you see an unwholesome thought, stop that thought from forming other thoughts. Essentially the Buddha said to tell yourself to gradually slow down the mental (and physical) mess that this unwholesome thought is creating in you.
5. Fifth and final try: With clenched-teeth, tongue on the palate of the mouth, and fight evil mind with good mind. Just say “STOP” to yourself and stop that unnecessary thought.
The Buddha stopped here, so it means that No. 5 should work… if it is not, you are not trying hard enough.
Note: The above cannot be applied if we are not aware that we are having an unwholesome thought. We need to be aware, at every moment, of what we are doing (i.e. thinking). This is the basic frame of mindfulness that the Buddha told us to cultivate. It is not easy, because the mind tends to drift when you are not mindful, but this essential “basic mindfulness” need to be there to “live in the present moment.”
The key is to become conscious of the thoughts, which flow into your consciousness. When you observe, your "Real I" (RI) is able to judge the quality of those thoughts. When you feel they are unworthy, you will smile and know it to be such. Actually, nothing more is needed. Ever afterwards, your mind will recognize this silly thought and discard it!