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




















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

再修改處理函數(shù):





















再運行,這個函數(shù)才花費將近一秒鐘的時間!
在Collections中提供了很多這類的方法。
當兩個線程A和B同時訪問此函數(shù)的時候,假設theList.site()為5.優(yōu)先級高的線程A首先訪問訪問此函數(shù).線程A刪除了一個元素,假設當前索引為2.線程B開始訪問此函數(shù),而開始刪除索引為2的元素.由于索引2的元素已經(jīng)被線程A刪除了,所以線程B開始訪問的刪除的時候,會拋出空指針的異常.