I live in a monastery. This help a lot, because we are always busy engaged in activities meant for serving God. So we are very carefully no to associate with the opposite sex, no watching movies, no magazines, no visiting public places like movie theaters, restaurants, etc. and we always talking and praying about God, reading together, eating together, going out together. So, association is very important, one can refraining and even forget about sex and masturbation. Here we have 20 or more years without indulging in sex and masturbation, because we are always together day and night, we don't have "privacy" in order to contemplate in our mind those kinds of though of sex.
So, you just be careful what you see, hear, talk, read, and do. Make sure that everything you do, eat, drink, hear, talk, think, etc, is for the pleasure of God, no for your pleasure. When you begin to think in yourself, in your selfish pleasure, then you fall down in this problems.
I made anonymous because I don't want publicity myself.