预增量运算符是否是线程安全的? [英] Is the pre-increment operator thread-safe?
问题描述
我正在用java制作一个相互竞争的汽车程序。每辆车都是一个单独的线程。
I'm making a program in java that races a few cars against each other. Each car is a separate thread.
当汽车完成比赛时,每个人都会调用此方法。我已经在不同的定时器速度下测试了这个方法,它似乎工作正常。但我确实意识到每个线程都在访问变量carsComplete,有时是在同一时间(至少在date命令给我的范围内)。
When cars complete the race, each one all calls this method. I've tested the method at varying timer speeds, and it seems to work fine. But I do realize that each thread is accessing the variable carsComplete, sometimes at the exact same time (at least at the scope the date command is giving me).
所以我的问题是:这个方法是线程安全的吗?
So my question is: is this method thread-safe?
public static String completeRace()
{
Date accessDate = new Date();
System.out.println("Cars Complete: " + carsComplete + " Accessed at " + accessDate.toString());
switch(++carsComplete)
{
case 1: return "1st";
case 2: return "2nd";
case 3: return "3rd";
default: return carsComplete + "th";
}
}
推荐答案
否,你应该使用像 java.util.concurrent.atomic.AtomicInteger
这样的东西。看看它的 getAndIncrement()
方法。
No, you should be using something like java.util.concurrent.atomic.AtomicInteger
. Look at its getAndIncrement()
method.
这篇关于预增量运算符是否是线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!