在使用多线程时,可能会访问一些全局的数据,这时必然会使用同步机制来使程序按照一定顺序来执行,这样程序的性能也会下降。所以一定要慎用同步,正确用同步。看下面的程序
localCriticalSection做为一个信号量来控制程序对类成员变量theList的访问,从而保证了theList在同一时间只有一个程序访问。运行程序,这个函数花费了将近4秒钟。同步是很耗时间的。
在java.util.Collections中提供了很多方法来保证集合(数组)的同步访问。
我们修改类成员变量theList的实例化方法:
再修改处理函数:
再运行,这个函数才花费将近一秒钟的时间!
在Collections中提供了很多这类的方法。
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++;
}
}
}
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++;
}
}
}
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中提供了很多这类的方法。