gpt4 book ai didi

java - 为什么不会发生死锁

转载 作者:行者123 更新时间:2023-12-01 19:36:13 24 4
gpt4 key购买 nike

Deadlock describes a situation where two more threads are blocked because of waiting for each other forever. When deadlock occurs, the program hangs forever and the only thing you can do is to kill the program.

为什么在下面给出的示例生产者消费者问题中不会发生死锁:

我想知道为什么当同步对象正在等待其他线程释放锁时,在同步块(synchronized block)中调用 wait 方法不会导致死锁?

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class WaitAndNotify {

public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
var th1 = new Thread(new Producer(list));
var th2 = new Thread(new Consumer(list));
th1.start();
th2.start();
}
}

class Producer implements Runnable {

private List<Integer> list;
private final Integer MAX_SIZE_LIST = 5;

public Producer(List<Integer> list) {
this.list = list;
}

@Override
public void run() {
Random rand = new Random();
for (;;) {
synchronized (this.list) {
if (list.size() == MAX_SIZE_LIST) { // check list is full or not
try {
System.out.println("list full wait producer");
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
var randNumber = rand.nextInt();
System.out.println("produce number => " + randNumber);
list.add(randNumber);
list.notify();
}
}
}

}

class Consumer implements Runnable {

private List<Integer> list;

public Consumer(List<Integer> list) {
this.list = list;
}

@Override
public void run() {
for (;;) {
synchronized (this.list) {
if (list.size() == 0) {
try {
System.out.println("list empty consumer wait");
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("consume number <= " + list.remove(0));
list.notify();
}
}
}
}

最佳答案

您可能认为,Consumer 将在 list.wait() 处阻塞,而 Producer 将在 synchronized (this.list) 处阻塞。

它有效,因为 list.wait() 释放了 synchronized block 内 list 的所有权。 wait返回后,线程再次获得所有权。

参见Object.wait()

关于java - 为什么不会发生死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57423836/

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