gpt4 book ai didi

java - 多线程java中的一进一出要求与统一服务员要求

转载 作者:行者123 更新时间:2023-11-30 02:50:24 25 4
gpt4 key购买 nike

在解释多线程中的有界缓冲区示例时,以下术语是什么:

1.一进一出要求

2.服务员统一要求

我在书中看到以下说法java concurrency in practice

BoundedBuffer meets the one-in, one-out requirement, but does not meet the uniform waiters requirement because waiting threads might be waiting for either the “not full” and “not empty” condition.

有人可以向我解释一下这两个术语及其区别吗?

谢谢

最佳答案

这些术语指的是在任意监视器上 wait() 的线程:

  • 统一等待者:WAITING线程是“平等的”,即它们等待相同的条件变为真。
  • 一进一出:有关条件的通知最多允许一个线程继续。

只有在满足两个属性时才应使用 notify(),否则调用 notifyAll()(尽管效率较低)。

Goetz 在第 303 页对此进行了解释,并给出了两个具体示例:

BoundedBuffer meets the one-in, one-out requirement, but does not meet the uniform waiters requirement because waiting threads might be waiting for either the "not full" [producers block on put] and "not empty" [consumers block on take] condition". A "starting gate" latch […] in which a single event releases a set of threads, does not meet the one-in, one-out requirement because opening the starting gate lets multiple threads proceed.

您还可以使用 java.util.concurrent 中的类来演示这一点:

BlockingQueue<String> queue = new ArrayBlockingQueue<>(1);

new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(1L);
System.out.println("Producer starts.");
queue.put("foo");
} catch (InterruptedException e) { /* NOP */ }
}).start();

try {
System.out.println("Consumer starts.");
System.out.println(queue.take());
} catch (InterruptedException e) { /* NOP */ }

消费者必须等待生产者将“foo”放入队列。两者等待不同的条件,因此, BlockingQueue不符合服务员统一要求。

另一方面,CountDownLatch满足服务员统一要求,但不满足一进一出要求。一旦锁存器达到零,所有等待线程都会被释放:

CountDownLatch latch = new CountDownLatch(1);
Runnable r = () -> {
try {
latch.await();
System.out.println("Thread proceeds.");
} catch (InterruptedException e) { /* NOP */ }
};

new Thread(r).start();
new Thread(r).start();

try {
TimeUnit.SECONDS.sleep(1L);
System.out.println("Count down.");
latch.countDown();
} catch (InterruptedException e) { /* NOP */ }

关于java - 多线程java中的一进一出要求与统一服务员要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38857942/

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