gpt4 book ai didi

Java:实现自己的消息队列(线程安全)

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:50:38 26 4
gpt4 key购买 nike

任务是实现我自己的线程安全的消息队列。

我的方法:

public class MessageQueue {
/**
* Number of strings (messages) that can be stored in the queue.
*/
private int capacity;

/**
* The queue itself, all incoming messages are stored in here.
*/
private Vector<String> queue = new Vector<String>(capacity);

/**
* Constructor, initializes the queue.
*
* @param capacity The number of messages allowed in the queue.
*/
public MessageQueue(int capacity) {
this.capacity = capacity;
}

/**
* Adds a new message to the queue. If the queue is full,
* it waits until a message is released.
*
* @param message
*/
public synchronized void send(String message) {
//TODO check
}

/**
* Receives a new message and removes it from the queue.
*
* @return
*/
public synchronized String receive() {
//TODO check
return "0";
}
}

如果队列为空并且我调用了 remove(),我想调用 wait() 以便另一个线程可以使用 send() 方法。分别地,我必须在每次迭代后调用 notifyAll() 。

问题:这可能吗?我的意思是,当我在一个对象的一个​​方法中说 wait() 时,我可以执行同一对象的另一个方法吗?

还有一个问题:这看起来很聪明吗?

最佳答案

Question: Is that possible? I mean does it work that when I say wait() in one method of an object, that I can then execute another method of the same object?

是的!这正是 wait 和 notify/notifyAll 的设计方式。如果您在一个对象上调用 wait(),那么该线程会阻塞,直到另一个线程在同一对象上调用 notify/notifyAll。

And another question: Does that seem to be clever?

是的!这正是我将(并且已经)使用低级 Java 操作实现消息队列的方式。


如果您有兴趣,这里有一个 BlockingQueue标准库中的类正是这样做的。如果只想使用这样的类,请使用 BlockingQueue。不过,如果您的目标是学习如何实现消息队列,请继续您的方法,这是完全正确的。

public interface BlockingQueue<E>
extends Queue<E>

A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

关于Java:实现自己的消息队列(线程安全),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13671502/

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