任务是实现一个线程安全的自己的消息队列。
我的方法:
如果队列为空并且我调用remove()方法,我希望调用wait()方法以便另一个线程可以使用send()方法。相应地,我必须在每次迭代后调用notifyAll()方法。
问题:这种情况是否可行?我的意思是当我在对象的一个方法中调用wait()方法时,我是否可以执行同一对象的另一个方法?
还有一个问题:这样做是否聪明?
我的方法:
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()方法时,我是否可以执行同一对象的另一个方法?
还有一个问题:这样做是否聪明?