How to Ensure thread security in Java

Source: Internet
Author: User

 

Nonsense opening

Java programs are better, But I think Java programming has never been able to say that I am proficient in Java programming for more than ten years. Due to work reasons, I started to fight Java multithreading, I have never been touched before, so I want to keep some footprints on these two roads.

Start with the topic

It's easy to read an article about whether the method is thread-safe. However, as I was just getting started, I took the first step. Because the comments are still relatively detailed, so we will not talk nonsense, directly go to the code.

This method is not a thread-safe NotThreadSafeCounter counter = 0 System. out. println ("counter:" + Thread. sleep (1500} counter ++ (I = 0; I <5; I ++} View Code this method is thread-safe (synchronized) counter = 0 System. out. println ("counter:" + counter ++ (I = 0; I <5; I ++} View Code this method is also thread-safe (AtomicInteger) atomicInteger counter = AtomicInteger (0 System. out. println ("counter:" + (I = 0; I <5; I ++} View Code time tail

I just got started. If you have any questions, please give me more advice and exchange.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.