Is the pre-increment operator thread-safe?

前端 未结 5 618
孤城傲影
孤城傲影 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 17:55

    Pre-increment on int is not thread safe, use AtomicInteger which is lock-free:

    AtomicInteger carsComplete = new AtomicInteger();
    
    //...
    
    switch(carsComplete.incrementAndGet())
    

    BTW the code below is not thread safe as well. Can you tell why?

    carsComplete.incrementAndGet();
    switch(carsComplete.get())
    

提交回复
热议问题