在below code listings
中,語句1和語句2是否安全?他們正在使用VolatileIntWrapper
。在多線程應用程序中使用帶易失性基元的條件運算符是安全的
如果它們不是線程安全的,哪些語句需要包裝在同步塊中?
public class Demo {
public static void main(String[] args) {
VolatileIntWrapper volatileIntWrapper = new VolatileIntWrapper() ;
for(int i = 1 ; i <= 5 ; ++i){
new ModifyWrapperIntValue(volatileIntWrapper).start() ;
}
}
}
class VolatileIntWrapper{
public volatile int value = 0 ;
}
class ModifyWrapperIntValue extends Thread{
private VolatileIntWrapper wrapper ;
private int counter = 0 ;
public ModifyWrapperIntValue(VolatileIntWrapper viw) {
this.wrapper = viw ;
}
@Override
public void run() {
//randomly increments or decrements VolatileIntWrapper primitive int value
//we can use below statement also, if value in VolatileIntWrapper is private
// wrapper.getValue() instead of wrapper.value
//but, as per my understanding, it will add more complexity to logic(might be requires additional synchronized statements),
//so, for simplicity, we declared it public
//Statement 1
while(wrapper.value > -1500 && wrapper.value < 1500){
++counter ;
int randomValue = (int) (Math.random() * 2) ;
//Statement 2
wrapper.value += (randomValue == 0) ? 1 : -1 ;
}
System.out.println("Executed " + counter + " times...");
}
}
它示出了定義:'類VolatileIntWrapper { 公共揮發性int值= 0; }' – GingerHead 2012-07-13 05:58:01
謝謝@Mike。忽略了。 – Gray 2012-07-13 05:59:40
@格雷:感謝這個詳細而又好的解釋......接受。 – mogli 2012-07-13 06:49:08