Honestly like someone else said, look into NoFap and also meditation. This is for if you are so addicted that it’s negatively affecting your life, and that’s when you know you need to make a change and do something about it. If it’s only sometimes and not ruining your life, then you don’t need to do all of this.
When I was addicted to porn and masturbation what I did was stop thinking about those things and redirecting my focus on things they really matter to me. That means focusing on your work and passions. A way to control your thoughts is to start meditating. I recommend doing 10 minutes a day, whether it’s night or morning, and what I did was I started doing this, then progressing to two times a day for 10 minutes each. Why I recommend meditation is because it actually helps you control your thoughts better by practicing focusing on something for a continuous time.
You should also delete any thing that would trigger you and look into the NoFap reddit