同步(synchronized)对程序性能的影响!

在使用多线程时,可能会访问一些全局的数据,这时必然会使用同步机制来使程序按照一定顺序来执行,这样程序的性能也会下降。所以一定要慎用同步,正确用同步。看下面的程序
None.gif        int  curIndex  =   0 ;
None.gif        AuditQueueEntry aqe;
ExpandedBlockStart.gifContractedBlock.gif        
synchronized  (localCriticalSection)  dot.gif {      
ExpandedSubBlockStart.gifContractedSubBlock.gif            
while (curIndex < theList.size()) dot.gif{
InBlock.gif                aqe 
= (AuditQueueEntry) theList.get(curIndex);
ExpandedSubBlockStart.gifContractedSubBlock.gif                
if (aqe.getTrailId() == theTrailId) dot.gif{
InBlock.gif                    theList.remove(curIndex);
ExpandedSubBlockStart.gifContractedSubBlock.gif                }
 else dot.gif{
InBlock.gif                    curIndex
++;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }

localCriticalSection做为一个信号量来控制程序对类成员变量theList的访问,从而保证了theList在同一时间只有一个程序访问。运行程序,这个函数花费了将近4秒钟。同步是很耗时间的。
在java.util.Collections中提供了很多方法来保证集合(数组)的同步访问。
我们修改类成员变量theList的实例化方法:
None.gif theList  =  Collections.synchronizedList(new LinkedList());

再修改处理函数:
None.gif          int  curIndex  =   0 ;
None.gif        AuditQueueEntry aqe;
None.gif
//         synchronized (localCriticalSection) {
ExpandedBlockStart.gifContractedBlock.gif
         synchronized (theList)  dot.gif {    
ExpandedSubBlockStart.gifContractedSubBlock.gif            
while (curIndex < theList.size()) dot.gif{
InBlock.gif                aqe 
= (AuditQueueEntry) theList.get(curIndex);
ExpandedSubBlockStart.gifContractedSubBlock.gif                
if (aqe.getTrailId() == theTrailId) dot.gif{
InBlock.gif                    theList.remove(curIndex);
ExpandedSubBlockStart.gifContractedSubBlock.gif                }
 else dot.gif{
InBlock.gif                    curIndex
++;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }

再运行,这个函数才花费将近一秒钟的时间!
在Collections中提供了很多这类的方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值