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<thread> list = new ArrayList<thread>(); long start = System.currentTimeMillis(); for(int j=0;j<p style="text-align: left;">Execution result:</p> <p style="text-align: center;"><img src="https://img.php.cn//upload/image/892/587/606/1540201251389022.png" title="1540201251389022.png" alt="How to implement thread-safe counter in java? How to implement a thread-safe counter"></p></thread></thread>
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!