Home> Java> javaTutorial> body text

How to implement thread-safe counter in java? How to implement a thread-safe counter

青灯夜游
Release: 2018-10-22 17:45:27
forward
5378 people have browsed it

What this article brings to you is how to implement thread-safe counters in Java? How to implement a thread-safe counter. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

  • Introduction to the implementation principle of thread-safe counters:
    The volatile keyword in Java can ensure the visibility of shared data, and it will update the data. Refresh the working memory into the shared memory, invalidate the data in the working memory in other threads, and then read the latest value from the main memory to ensure the visibility of the shared data. The thread-safe counter is implemented through cyclic CAS operations. It is to first obtain an old expected value, and then compare whether the obtained value is consistent with the value in the main memory. If they are consistent, update them. If they are inconsistent, continue to loop until success.

  • Specific code implementation

public class Count{ private int count = 0; private AtomicInteger atomicI = new AtomicInteger(0); public static void main(String[] args){ final Count cas = new Count(); List list = new ArrayList(); long start = System.currentTimeMillis(); for(int j=0;j

Execution result:

How to implement thread-safe counter in java? How to implement a thread-safe counter

Copy after login

The above is the detailed content of How to implement thread-safe counter in java? How to implement a thread-safe counter. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!