This topic has been archived. It cannot be replied.
-
工作学习 / 专业技术讨论 / 多线程小问题public class Counter {
private int counter;
public Counter() {
counter = 0;
}
public synchronized int getCounter() {
return counter;
}
public synchronized int setCounter(int c) {
counter = c;
return counter;
}
public synchronized int incCounter() {
return(++counter);
}
}
这个get method有必要synchronize吗?谢谢
-aaronding(流浪的八毛儿);
2007-3-26
{367}
(#3577010@0)
-
有必要。
-keepbugging(独行的猫);
2007-3-26
(#3577264@0)
-
为啥呢?
-aaronding(流浪的八毛儿);
2007-3-26
(#3577270@0)
-
该数据更新的同时去读取,则读取的数据有可能是不完整的。
-keepbugging(独行的猫);
2007-3-26
(#3577277@0)
-
no, it's integer and won't be crupted because write to an integer will be done by 1 instruction. It's not possible to change partially. If the data is a structure or string or soemthing other than basic data type, it's necessary to synchronize.
-wangqingshui(忘情水);
2007-3-27
(#3579476@0)
-
So you think Microsoft provides "InterlockedIncrement" just for fun?
-holx(Dicom);
2007-3-27
(#3580184@0)
-
increment is different. I was talking about getCounter(), not incCounter().
-wangqingshui(忘情水);
2007-3-27
(#3580314@0)
-
Above is valid in C age, but in java, even int need sync
-xordos(donothing);
2007-3-27
(#3580270@0)
-
You are right. When the JVM is running on a 8-bit or 16-bit machine, 32-bit read can not be done in 1 machine instruction.
-wangqingshui(忘情水);
2007-3-27
(#3580335@0)
-
32bit even 64bit still need, you can take a look the javap output
-xordos(donothing);
2007-3-27
(#3580468@0)
-
really? I bet not, in C languauge the integer assignment operation will be converted to at least three CPU instuctions.
-frankwoo(柳五随风);
2007-3-28
(#3582488@0)
-
弄明白了,有必要。
-aaronding(流浪的八毛儿);
2007-4-12
(#3610474@0)