在使用多線程時,可能會訪問一些全局的數據,這時必然會使用同步機制來使程序按照一定順序來執行,這樣程序的性能也會下降。所以一定要慎用同步,正確用同步。看下面的程序
??????? int?curIndex?=?0;
????????AuditQueueEntry?aqe;
????????
synchronized?(localCriticalSection)?{??????
????????????
while?(curIndex?<?theList.size())?{
????????????????aqe?
=?(AuditQueueEntry)?theList.get(curIndex);
????????????????
if?(aqe.getTrailId()?==?theTrailId)?{
????????????????????theList.remove(curIndex);
????????????????}
?else?{
????????????????????curIndex
++;
????????????????}

????????????}

????????}

localCriticalSection做為一個信號量來控制程序對類成員變量theList的訪問,從而保證了theList在同一時間只有一個程序訪問。運行程序,這個函數花費了將近4秒鐘。同步是很耗時間的。
在java.util.Collections中提供了很多方法來保證集合(數組)的同步訪問。
我們修改類成員變量theList的實例化方法:
theList?=?Collections.synchronizedList(new?LinkedList());

再修改處理函數:
????????int?curIndex?=?0;
????????AuditQueueEntry?aqe;
//????????synchronized?(localCriticalSection)?{
????????synchronized(theList)?{????
????????????
while?(curIndex?<?theList.size())?{
????????????????aqe?
=?(AuditQueueEntry)?theList.get(curIndex);
????????????????
if?(aqe.getTrailId()?==?theTrailId)?{
????????????????????theList.remove(curIndex);
????????????????}
?else?{
????????????????????curIndex
++;
????????????????}

????????????}

????????}

再運行,這個函數才花費將近一秒鐘的時間!
在Collections中提供了很多這類的方法。