Atomic Operations and multithreading

后端 未结 6 1339
一整个雨季
一整个雨季 2020-12-13 04:47

Recently I was reading a tutorial, in that I came across a statement that says..

\"The Java language specification guarantees that reading or writing a variable is

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-13 05:23

    I think what it means is that long and double - read operation is atomic and write operation is atomic. But a read + write is not atomic.

    volatile long num;
    num = num+1
    

    The above is not thread safe. There read and write are two separate operations. Each of those are guaranteed to be atomic, but the whole expression is not.

    To make it thread safe you would need to use an AtomicLong and use the getAndIncrement function.

提交回复
热议问题