我在網上搜索一個生產者消費者問題和我有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