我在网上搜索一个生产者消费者问题和我有this link上同步的需要。 程序员使用矢量这里的sharedqueue
。什么是线程安全的对象
我想为什么我需要一个同步块作为向量已经线程安全。它必须自己处理线程。
但是当我试图通过移除synchronized块做到这一点。它给了我一个IllegalMonitorStateException
。以下是代码片段生产方法
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()的文档:它清楚地表明您需要有锁才能调用这些方法。 – 2014-09-27 14:39:21