Java:实现自己的消息队列(threadsafe)

der*_*Max 3 java concurrency message-queue

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

我的方法:

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

另一个问题:这似乎是聪明的吗?

Joh*_*ica 6

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

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

另一个问题:这似乎是聪明的吗?

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


如果您有兴趣,标准库中有一个BlockingQueue类就可以完成此操作.如果您只想使用这样的类,请使用BlockingQueue.但是,如果您的目标是学习如何实现消息队列,请继续使用您的方法,这是完全正确的.

public interface BlockingQueue<E>
extends Queue<E>
Run Code Online (Sandbox Code Playgroud)

一个队列,它还支持在检索元素时等待队列变为非空的操作,并在存储元素时等待队列中的空间可用.