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

3
任务是实现一个线程安全的自己的消息队列。
我的方法:
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()方法时,我是否可以执行同一对象的另一个方法?
还有一个问题:这样做是否聪明?
1个回答

7

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

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

还有一个问题:这似乎很聪明吗?

是的!这正是我使用低级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.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接