문제

Here is the example.

class Factory {
    Queue<Object> queue = new LinkedBlockingQueue<Object>();

    public Object consume() {
        queue.take();
    }

    public void produce() {
        for (int i = 0; i < 2; i++) {
            queue.put(new Object());
        }
    }
}

For example I have two threads which both called consume(). They are waiting for a producer to put something in the queue. My question is whether after a put() action a take() action happens, or is it possible for two put() actions to happen one after the other and only after that the waiting threads will return ?

Thank you.

도움이 되었습니까?

해결책

As soon as put finishes, lock is released now lets assume put and take both are waiting on that lock again and its unfair lock then any of the methods Put/Take can get hold of lock and start. There is no ordered and alternate exchange of monitor(lock) unless specified.

See the code by java.

ArrayBlockingQueue

ReentrantLock

AbstractQueuedSynchronizer

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top