In JAVA multithreading, the concept of atomic operations-Do atomic operations really require no synchronization control?

Source: Internet
Author: User

[Java] import java. util. concurrent. executorService; import java. util. concurrent. executors; class Sd implements Runnable {private int a = 1; public int getA () {return a;} private synchronized void oddIncrement () {a ++ ;} @ Override public void run () {// TODO Auto-generated method stub while (true) {oddIncrement ();}}} public class SychronizedDemo {public static void main (String [] args ){ ExecutorService es = Executors. newCachedThreadPool (); Sd sd = new Sd (); es.exe cute (sd); while (true) {int B = sd. getA (); if (B % 2 = 0) {System. out. println (B); System. in the exit (0) ;}}} program, we can see that the initial value of a is 1, and then the oddIncrement () operation is two consecutive value-added operations for, so one call is + 2, so no matter how many value-added operations a has performed, it is an odd number. Then, in the main function, we can determine the operation of % 2 = 0, in principle, it should be impossible, but on the contrary, even B values will still be printed on the console. This indicates that atomic operations require synchronous control. So what is the problem above? In my opinion, in the getA method, there are definitely some operations between the getA and oddIncrement methods that lead to deviations between the getA value and the oddIncrement method. Although the oddIncrement operation on www.2cto.com was synchronized, the getA operation was not synchronized. We tried to synchronize the getA method [java] public synchronized int getA () {return a;}. When we ran the above program again, we found that the console had not output for a long time. I think this should be okay. Therefore, in JAVA programs, it seems that simple atomic operations, value-added, and values will not be interrupted by other programs, but this is not the case.

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.