You can protect yourself against HIV infection by using a condom and avoid using needles that others have used. There are also anti-HIV medicines called PrEP (pre-exposure prophylaxis) and it can be given to people at high risk of getting HIV. This is only offered to those where there is a strong indication and who are defined as risk persons. These include men who have sex with men and transgender people who have had unprotected intercourse with several partners in the last 12 months with a high risk of recurrence.
If you are in a situation where there is a high probability that you are infected with HIV (eg after a needle stick from a needle used by someone with HIV, unprotected intercourse with someone with a known infection) then there is also a treatment you can get shortly after possible infection to stop a possible infection. It is important that this is taken 48 hours before the time of infection for it to have an effect.
Today, there is also good treatment if you have been infected with HIV. This is a lifelong treatment consisting of three different antiviral drugs (drugs that remove viruses.)