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 。
最佳答案
生产者进入同步块(synchronized block)并向列表添加 11 个元素。由于 11 大于 10,因此它会等待,从而释放锁,允许使用者进入同步块(synchronized block)。
然后,消费者在同步块(synchronized block)内启动无限循环,在每次迭代时从列表中删除一个元素。它永远不会调用 wait()
并且也永远不会跳出 while 循环。所以它永远不会释放锁,并永远保持迭代。读取第 11 个元素后,列表为空,因此出现异常。
关于java - 我的 2 个线程在这里是生产者和消费者。当我运行程序时,它在removeFirst() 调用上抛出 nosuchelementexception。有人可以解释一下吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33597656/