我有一個關於使用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