It’s a matter of training and practice. Specifically, you need to learn by direct observation how your attention functions, how thoughts function, and how the two interact. There are several meditation practices aimed at doing exactly this, giving you a front row seat for studying how your mind works.
What gets “controlled” is not the thoughts, but the attention. Thoughts constantly arise in the mind; we can’t stop that. But what becomes of them is strictly a matter of attention, and that we can direct. Meditators learn that when we become aware that a thought has arisen, we can choose not to allow our attention to go to it. Deprived of attention, all thoughts naturally just fade and vanish. If, on the other hand, attention is given to a thought, it assumes a life of its own, chaining off into a long succession of other thoughts.
There are times when thoughts are not our friends, when we’re better off allowing our attention to rest on the reality unfolding around us instead of on our thoughts and inner discourse. At times like this (and there are lots of them), it’s helpful to know that we can simply not allow our attention to be drawn off into our thoughts and that they will all just come and go on their own.
But there are plenty of other times when we need to think. The problem becomes that in giving the mind free rein to think, along with relevant, focused thoughts, tangential or unrelated thoughts will inevitably arise. Here, training allows you see the trap of distraction before you venture too far down that path to easily recover. You have the choice of directing the attention at worthwhile thoughts, and letting the irrelevant “noise” go.
There are many forms of meditation making the rounds these days, some time-tested and reliable, others faddish and ineffective. I have my own preferences, but I’m not here to push it on anyone else. There’s a whole heap of material, good and bad, online and in print, but eventually you’ve just got to stop reading about it and get to work. Don’t expect quick fixes; it takes lots of patient practice to undo a lifetime of sloppy mental habits.