【发布时间】:2010-12-09 02:19:35
【问题描述】:
我有一个保证跨线程可见的集合。但是,这并不能保证存储在此集合中的项目状态的可见性(例如,如果我有 StringBuilder 的集合(可变的,不是线程安全的),那么我必须在写入/读取期间同步集合中的每个项目,对吗? )。所以,当我收集用于保证先发生的对象时会发生什么(例如倒计时)。调用 await/countDown 时是否需要以某种方式同步每个项目?下面的代码大致说明了这种困境:
public class SyncQuestion {
final List<CountDownLatch> lathces = new ArrayList<CountDownLatch>();
SyncQuestion() {
lathces.add(new CountDownLatch(1));
}
public static void main(String[] args) throws InterruptedException {
final SyncQuestion sync = new SyncQuestion();
final Thread sleepingThread = new Thread() {
public void run() {
for (CountDownLatch latch : sync.lathces) {
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
};
};
final Thread wakingThread = new Thread() {
public void run() {
for (CountDownLatch latch : sync.lathces) {
latch.countDown();
}
};
};
sleepingThread.start();
wakingThread.start();
sleepingThread.join();
wakingThread.join();
}
}
如果我的假设是错误的,请纠正我的假设。
【问题讨论】:
标签: java multithreading synchronization locking thread-safety