我有一个关于使用runnable在单身人士中工作的问题。如何使用runnable在Singleton中工作?
我有一个EventCoordinator类,它是一个单例,因为它是处理所有事件的一个(因为我的任务需要我这样做)。 事件将被添加到此协调器中,并将在稍后处理。 必须在不同的线程中处理事件,在该线程中,运行将处理队列的事件并对其进行处理。 start方法应该启动一个新的线程,该线程使用run来接收队列的事件。
final public class EventCoordinator implements Runnable {
protected final static EventCoordinator coordinator = new EventCoordinator();
protected static LinkedList<QueueItem> queue = new LinkedList<QueueItem>();
private EventBroker() {
}
private class QueueItem {
protected Event event;
public QueueItem(Event event) {
this.event = event;
}
}
public static EventCoordinator getEventCoordinator() {
return coordinator;
}
public void addEventObserver(EventObserver o) {
//adds listeners to the coordinator
}
void addEvent(EventPublisher source, Event e) {
QueueItem queueItem = new QueueItem(e, source);
synchronized(this) { queue.add(queueItem); }
}
public void run() {
// Process items from the queue
}
public void start() {
// start a new thread that processes items of the queue
}
}
但据我所知可运行的方式是,当你创建一个thread = new Thread(New EventCoordinator)
您创建一个新的EventCoordinator对象,因而不工作在同一个队列了。 那么如何使用runnable来完成队列的这项工作呢?我是否使队列静态?我是否实现了方法来添加和删除队列中的项目,并且在由getEventCoordinator返回的协调器上调用它们?
1)使用'BlockingQueue'。 3)摆脱所有'synchronized'块。 3)你基本完成了。 –
为什么你不能只是'线程=新的线程(协调器)'? – OldCurmudgeon
@Deb您选择哪个答案为最佳答案?你能找到解决办法吗? – Saidolim