【发布时间】:2017-06-07 17:36:39
【问题描述】:
在 Programming Interviews Exposed 一书(Wrox 出版物)中,生产者消费者问题的代码对名为 IntBuffer 的类中的每个生产()和消费()方法都使用了“同步”关键字。这与在每个方法中使用 synchronized(this) 有什么不同吗?书中说,“当一个线程忙于在produce()中等待时,没有线程可以进入consume(),因为方法是同步的。”我觉得这对书中的代码没有意义,因为当一个线程忙于在produce()中等待时,没有线程可以进入produce()。然而,其他线程可以进入consume(),这打破了互斥的想法。生产和消费的方法应该完全同步吧?
书中代码:
public class IntBuffer
{
private int index;
private int[] buffer = new int[8];
// Function called by producer thread
public synchronized void produce(int num) {
while(index == buffer.length - 1) {
try { wait();}
catch(InterruptedException ex) {}
}
buffer[index++] = num;
notifyAll();
}
// Function called by consumer thread
public synchronized int consume() {
while(index == 0) {
try { wait();}
catch(InterruptedException ex) {}
}
int ret = buffer[--index];
notifyAll();
return ret;
}
}
【问题讨论】:
-
标记方法
synchronized同步this,就像synchronized (this)块一样。它没有在方法或类似的东西上同步。 -
The methods produce and consume should both entirely be synchronized right ?通常,是的,生产者和消费者都需要在同一个对象上同步。我认为我们需要查看确切的代码才能确定。
标签: java synchronized