public class Processor {
LinkedList<Integer> list = new LinkedList<Integer>();
public static final int LIMIT = 10;
public void producer() throws InterruptedException {
Random random = new Random();
synchronized (this) {
while (true) {
list.add(random.nextInt(100));
if (list.size() > LIMIT) {
wait();
}
}
}
}
public void consumer() throws InterruptedException {
Thread.sleep(1000);
synchronized (this) {
while (true) {
int value = list.removeFirst();
System.out.println("removed value is..." + value);
if (list.size() < LIMIT) {
notify();
}
}
}
}
}
请解释为什么我在上面的代码中没有这样的元素异常。 生产者和消费者是 2 个线程,如果我运行,我会在 removeFirst(( 上得到 nosuchelementexception。
生产者进入同步块并将 11 个元素添加到列表中。由于 11 大于 10,因此它会等待,从而释放锁,允许使用者进入同步块。
然后,使用者在同步块内启动无限循环,在每次迭代时从列表中删除一个元素。它从不调用wait()
,也永远不会脱离 while 循环。因此,它永远不会释放锁,并且永远不断迭代。读取第 11 个元素后,列表为空,因此异常。