【问题标题】:Java: Implement own message queue (threadsafe)Java:实现自己的消息队列(线程安全)
【发布时间】:2012-11-20 05:24:28
【问题描述】:

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

我的做法:

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() 时,我可以执行同一个对象的另一个方法吗?

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

【问题讨论】:

    标签: java concurrency message-queue


    【解决方案1】:

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

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

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

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


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

    public interface BlockingQueue<E>
    extends Queue<E>
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 2012-05-30
      • 2018-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      相关资源
      最近更新 更多