gpt4 book ai didi

java - 生产者/消费者死锁原因及调试

转载 作者:行者123 更新时间:2023-12-02 06:00:06 25 4
gpt4 key购买 nike

虽然以下是众所周知的话题,但我想请您提供意见。我写了一个小程序如下:所有生产者和消费者都排队。我不明白为什么会这样。什么场景下可以完全阻塞。

让我们考虑一下生产者/消费者正在等待数组上的锁,以及是什么让消费者/生产者退出同步块(synchronized block)。我的意思是它必须至少缓慢地移动,但决不能发生僵局。我相信。

这里我有两个问题:1. 死锁发生的场景有哪些。2. 如何理解幕后发生的事情。我的意思是如何调试。

public class ProducerConsumer implements Runnable {

boolean producer = false;

private volatile int i = 0;

int[] array = new int[10];

public static String getThreadName() {
return Thread.currentThread().getName();
}

public void producer() {
try {
synchronized (array) {
while (i > 9) {
System.out.println("Producer of " + getThreadName()
+ " is waiting i " + i);
array.wait();
System.out.println("Producer of " + getThreadName()
+ " came out of sleep i " + i);
}
System.out.println("Producer of " + getThreadName()
+ " in synchronized block i" + i);
array[i] = generateRandom();
System.out.println("Producer of " + getThreadName()
+ " inserted in array " + array[i] + " index " + i);
i++;
array.notifyAll();
}
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println("Producer of " + getThreadName()
+ " interrupted " + e);
}

}

public void consumer() {
try {
synchronized (array) {
while (i < 0) {
System.out.println("Consumer of " + getThreadName()
+ " is waiting i " + i);
array.wait();
System.out.println("Consumer of " + getThreadName()
+ " came out of sleep i " + i);
}
System.out.println("Consumer of " + getThreadName()
+ " in synchronized block extracted value " + array[i]
+ " of index " + i);
i--;
array.notifyAll();
}
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println("Consumer of " + getThreadName()
+ " interrupted " + e);
}

}

public static int generateRandom() {
Random random = new Random();
return random.nextInt(10);
}

public static void main(String[] args) {
ProducerConsumer pc = new ProducerConsumer();
for (int i = 0; i < 4; i++) {
if (i % 2 == 0)
new Thread(pc, "producer thread").start();
else {
new Thread(pc, "consumer thread").start();
}
}
}

public void run() {
while (true) {
if (getThreadName().equalsIgnoreCase("producer thread")) {
producer();
} else {
consumer();
}
}

}
}

它的输出如下:

Consumer of consumer thread in synchronized block extracted value 0 of index 0
Producer of producer thread in synchronized block i-1
Producer of producer thread in synchronized block i-1
Consumer of consumer thread is waiting i -1
Consumer of consumer thread is waiting i -1

最佳答案

您的代码在很多地方都不正确。

我希望所有线程都以异常结束,要么是因为

  • IllegalMonitorException(在 ProducerConsumer 对象上调用 notification())但此 ProducerConsumer 对象上没有同步块(synchronized block))
  • ArrayIndexOfBoundsException(i 在 Produce() 方法中可以变为 10)

您检查过错误输出吗?

关于java - 生产者/消费者死锁原因及调试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22743786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com