0

こんにちは私は次のコードを持っています:

public Item get(int id)
{
    Item i = null;
    for(Worker w : workers)
    {
        w.get(id, i); // Several threads start reading that item from data sources
    }
    while(i == null) // Loop until item is found
    {
        // this.pause(); there should be a pause but it's not a thread, so I can't do it.
    }
    return i;
}

その空のループがなければ、もっと良い方法があるはずだと思います。

get関数を一時停止し、ワーカーの1人からの通知があった場合にのみ再開することを含む何か。

4

1 に答える 1

2

ここでBlockingQueueを使用できます。キューのインスタンスを作成します。そしてそれをすべての労働者に渡します。ワーカーがアイテムを見つけると、それをキューに追加します。そして、キューが空でなくなるまで待つだけです。

public Item get(int id) {
    BlockingQueue<Item> queue = new ArrayBlockingQueue<Item>(1);
    for(Worker w : workers) {
        w.get(id, queue); // Several threads start reading that item from data sources
    }
    return queue.take();
}

queue.offer(foundItem);キューが空の場合にのみアイテムを追加するようにワーカーで使用します。

于 2012-12-07T12:51:00.050 に答える