Here is a study that creates and manipulates the "song stuck in your head" phenomenon. In particular, it is a myth that only "bad" songs are stuck in your head. These songs can be categorized as intrusive thoughts. Also the obvious finding was that recently heard music was more likely to be stuck in your head.
The authors comes up with a term called the "Goldilocks Effect." In particular, songs are more likely to be stuck in your head if you are doing a really easy or a really hard task. If you are doing a really easy task it is easy for your mind to think about other things (e.g. think about driving on a highway and being in a "highway hypnosis"). When you are doing a hard task sometimes a moment of relaxation and insight is needed. This is where songs often come up. Thus to control this, you should do an activity that is not too easy or too hard (or not too little or too much arousal following the Yerkes Dodson Law).
Going Gaga: Investigating, Creating, and Manipulating the Song Stuck in My Head
Ira E. Hyman Jr.*, Naomi K. Burland, Hollyann M. Duskin, Megan C. Cook, Christina M. Roy, Jessie C. McGrath, Rebecca F. Roundhill
Kounios, J., & Beeman, M. (2009). The Aha! Moment The Cognitive Neuroscience of Insight. Current Directions in Psychological Science, 18(4), 210-216.