在使用多線程時(shí),可能會(huì)訪問(wèn)一些全局的數(shù)據(jù),這時(shí)必然會(huì)使用同步機(jī)制來(lái)使程序按照一定順序來(lái)執(zhí)行,這樣程序的性能也會(huì)下降。所以一定要慎用同步,正確用同步。看下面的程序
??????? 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做為一個(gè)信號(hào)量來(lái)控制程序?qū)︻惓蓡T變量theList的訪問(wèn),從而保證了theList在同一時(shí)間只有一個(gè)程序訪問(wèn)。運(yùn)行程序,這個(gè)函數(shù)花費(fèi)了將近4秒鐘。同步是很耗時(shí)間的。
在java.util.Collections中提供了很多方法來(lái)保證集合(數(shù)組)的同步訪問(wèn)。
我們修改類成員變量theList的實(shí)例化方法:
theList?=?Collections.synchronizedList(new?LinkedList());

再修改處理函數(shù):
????????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
++;
????????????????}

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

????????}

再運(yùn)行,這個(gè)函數(shù)才花費(fèi)將近一秒鐘的時(shí)間!
在Collections中提供了很多這類的方法。