Is the pre-increment operator thread-safe?

前端 未结 5 614
孤城傲影
孤城傲影 2020-12-03 17:42

I\'m making a program in java that races a few cars against each other. Each car is a separate thread.

When cars complete the race, each one all calls this method.

5条回答
  •  渐次进展
    2020-12-03 18:09

    ++ operator is not atomic. Look at here http://madbean.com/2003/mb2003-44/. For atomic operations you can use AtomicInteger

    AtomicInteger atomicInteger = new java.util.concurrent.atomic.AtomicInteger(0)
    

    and every time you want to increment you can call atomicInteger.incrementAndGet() method which returns a primitive int. 0 is the default initial value for the atomic integer.

提交回复
热议问题