This is the 14th day of my participation in the August More Text Challenge

Some people think s=s+1; And s + = 1; It doesn’t make any difference, it’s s plus 1 and then it’s assigned to s, it doesn’t make any difference, but plus plus 1 is different from 1 plus plus. ++1 is the increment before assignment, and 1++ is the increment after assignment. Is it really so?

s=s+1,s+=1

To verify this, short s = 1; s = s + 1; Didn’t you? s += 1; Didn’t you? Does it look familiar? Isn’t that a common interview question? Do you know the answer? Short s = 1; s = s + 1; Since 1 is an int, s + 1 is also an int and requires a cast to assign to short. Short s = 1; s += 1; It compiles correctly because s += 1; S = (short)(s + 1); There is an implicit cast.

It’s not a surprise, it’s not a surprise.

+ + + + 1, 1

I don’t have to say anything more about this, but just like we said before ++1 is the increment before assignment, 1++ is the increment after assignment. My question is no longer this, but is ++1,1++ thread safe?

I don’t know, kid. Hey, hey. The test code

public class Test {

    static int count1 = 0;
    static int count2 = 0;
    static CountDownLatch countDownLatch = new CountDownLatch(100);

    public static void main(String[] args) throws InterruptedException {
        TestRunnable testRunnable = new TestRunnable();
        for (int i = 0; i < 100; i++) {
            new Thread(testRunnable).start();
        }
        countDownLatch.await();
        System.out.println("count1:" + count1);
        System.out.println(count2);
    }

    static class TestRunnable implements Runnable {

        private void count(a) {
            for (int i = 0; i < 1000; i++) { count1++; count2++; }}@Override
        public void run(a) { count(); countDownLatch.countDown(); }}}Copy the code

The results

/ / for the first time
count1:98867
count2:99013
/ / the second time
count1:99821
count2:99828
/ / the third time
count1:100000
count2:100000
/ / for the fourth time
count1:99672
count2:99682The fifth count1:98500
count2:98503
Copy the code

Yes, but do you know why?

In this case, a third variable k is introduced. At this point, the value of K is I, and then the increment operation is performed, and the value of I changes to 1. Finally, the assignment operation I = k (the value before the increment operation) is performed. From the above analysis, we know that the execution of the I = I ++ statement consists of multiple operations, not atomic operations, and therefore is not thread-safe.

Solution Java. Util. Concurrent AtomicInteger is an atomic operation of Integer type, it provides a thread safe and highly effective atomic operations, is thread safe. It’s not just the Integer Atomic package that has a lot of thread-safe operations, of course, and this is something you need to explore for yourself.