【发布时间】:2014-09-27 14:36:41
【问题描述】:
我在网上搜索生产者消费者问题,我得到了this link。
程序员在这里为sharedqueue 使用了一个Vector。
我想为什么我需要一个同步块,因为 Vector 已经是线程安全的。它必须自己处理线程。
但是当我试图通过删除同步块来做到这一点时。它给了我一个IllegalMonitorStateException。这是produce方法的代码sn-p
private void produce(int i) throws InterruptedException {
//wait if queue is full
while (sharedQueue.size() == SIZE) {
// synchronized (sharedQueue) {
System.out.println("Queue is full " + Thread.currentThread().getName()
+ " is waiting , size: " + sharedQueue.size());
sharedQueue.wait();
// }
}
//producing element and notify consumers
// synchronized (sharedQueue) {
sharedQueue.add(i);
sharedQueue.notifyAll();
// }
}
我的问题是为什么我们需要对已经是线程安全的对象进行同步或锁定?
【问题讨论】:
-
阅读 wait() 和 notify() 的文档:它清楚地表明您需要拥有锁才能调用这些方法。
标签: java multithreading vector thread-safety synchronized