Use mantras. I repeat the same thing to myself over and over and over again. For example, during the first part of the run I am thinking "Relaxed and flying, your pace, negative split, easy log run". Relaxed and flying is kind of a technical cue to get my striding flowing, your pace and negative split are about holding back and not getting caught up. "Easy Long Run" is also related to pace and feel. I find that by repeating those things over and over again, I am less likely to have a wandering mind and allow those thoughts to creep in.
I try and pre plan out what I want to think about during the race, especially in the moments that I think will be especially tough.
I also cheer other competitors on. This doesn't work in a 5k or an Olympic distance race, but during an Ironman you aren't really out of breath. But I find that when you are telling people good things, you are also cheering yourself on and boosting your spirits. And often times the other competitors will return the favor. If there aren't other competitors around, then I randomly yell "yeah" or "woo" to help pick me up. This works best if you spectators are around, or you are approaching an aid station. Saying "thank you" to volunteer helps too and is just an all round good idea.
I also tell my spectators before the race what I like to hear while I am out there. Even better, make sure lots of people know your favor catchphrase like "Get Ugly" so that you have more people cheering you on out there!
Another tip is to really have a good answer for the question "Why am I out here" Because at some point you will test yourself on this. Make sure that you have at least one answer that is something that can't be taken away from you on race day. "To inspire someone. To live a better lifestyle. To be a badass" Something like that. My worst races have come when I didn't have a clear why beyond things like "Winning. Kona spot. Prize Money" Those can be good motivations at some points during the race, and let be honest, you need to use every little bit of motivation you can to really crush and Ironman, but the other stuff is longer lasting and provides motivation during the bleak moments of a race when you need it the most.
I hope that helps.
Website - Follow Me On Strava - Follow Me On Instagram