【发布时间】:2014-12-15 04:28:11
【问题描述】:
假设我有两个列表:fooList 和 barList。另外,假设我有两个线程:第一个遍历 fooList,如果满足某些条件(条件为真),它会从 fooList 中删除元素并将其添加到 barList。第二个遍历 barList,如果其他条件为真,则从 barList 中删除元素,并将其添加到 fooList。
我的处理方式是:
private static Object sharedLock = new Object();
Thread t1 = new Thread() {
public void run() {
synchronized (sharedLock) {
for (Iterator<String> iterator = fooList.iterator(); iterator.hasNext();) {
String fooElement = iterator.next();
if (condition == true) {
iterator.remove();
barList.add(fooElement);
}
}
}
}
};
Thread t2 = new Thread() {
public void run() {
synchronized (sharedLock) {
for (Iterator<String> iterator = barList.iterator(); iterator.hasNext();) {
String barElement = iterator.next();
if (otherCondition == true) {
iterator.remove();
fooList.add(barElement);
}
}
}
}
};
我想知道的是我处理得当吗?是否存在竞争条件的可能性?有没有更好的方法来实现相同的功能?
编辑看起来正确的实现方法是:
Thread t1 = new Thread() {
public void run() {
for (String fooElement : fooList) {
if (condition == true) {
fooList.remove(fooElement);
barList.add(fooElement);
}
}
}
};
Thread t2 = new Thread() {
public void run() {
for (String barElement : barList) {
if (otherCondition == true) {
barList.remove(barElement);
fooList.add(barElement);
}
}
}
};
其中:fooList 和 barList 的类型均为 CopyOnWriteArrayList<String>
【问题讨论】:
-
如果您正在同步整个
run块,那么多线程毫无意义。 -
@ScaryWombat 所以,仅在条件下同步?
-
不,使用 JDK 中 List 的线程安全实现
标签: java multithreading list iterator thread-safety