To get around this I use the pomodoro technique [1] and [2]
I have also found quite a bit of success using paper lists; If I write down everything productive I need to get done (mostly on a high-level like 'look into bug nnnn') and only allow myself to work on the items on the list.
I also actively work on keeping my mind on task; if I find myself wandering off and thinking about something important I will write myself a quick note so that I can remember it later, this helps get it off my mind so I can get back to working.
[1] http://en.wikipedia.org/wiki/Pomodoro_Technique [2] http://www.pomodorotechnique.com/