Вопрос по java, concurrency, consumer, producer – Java-параллелизм: мультипроизводитель с одним потребителем

5

Error: User Rate Limit Exceeded

class Producer implements Runnable {

    private Consumer consumer;

    Producer(Consumer consumer) { this.consumer = consumer; }

    @Override
public void run() {
    consumer.send("message");
  }
}

Error: User Rate Limit Exceeded

ExecutorService executor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 20; i++) {
  executor.execute(new Producer(consumer));
}

Error: User Rate Limit Exceeded

class Consumer implements Runnable {

private Queue<String> queue = new ConcurrentLinkedQueue<String>();

void send(String message) {
    synchronized (queue) {
        queue.add(message);
        System.out.println("SIZE: " + queue.size());
        queue.notify();
    }
}

@Override
public void run() {
    int counter = 0;
    synchronized (queue) {
    while(true) {
        try {
            System.out.println("SLEEP");
                queue.wait(10);
        } catch (InterruptedException e) {
                Thread.interrupted();
        }
        System.out.println(counter);
        if (!queue.isEmpty()) {             
            queue.poll();
            counter++;
        }
    }
    }
}

}

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded Randomize
Error: User Rate Limit Exceeded Randomize
Error: User Rate Limit Exceededwait, notifyError: User Rate Limit ExceededConcurrentLinkedQueue, ExecutorServiceError: User Rate Limit Exceeded artbristol
Error: User Rate Limit Exceeded dhblah

Ваш Ответ

3   ответа
2

Notification (queue.notify() ) will get lost because there is no consumer thread waiting on it if 10ms has elapsed.

Producer will not be able to add to the queue since they can't acquire lock because lock is claimed again by the consumer.

10

void send(String message) {
    synchronized (queue) {
        queue.put(message);
        System.out.println("SIZE: " + queue.size());
    }
}

queue.take()

one

Error: User Rate Limit Exceeded Randomize
Error: User Rate Limit Exceeded Randomize
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded Randomize
Error: User Rate Limit ExceededBlockingQueueError: User Rate Limit Exceeded.put()Error: User Rate Limit Exceeded.take()Error: User Rate Limit Exceeded.add()Error: User Rate Limit Exceeded.poll().
2

notifynotifyAll

Error: User Rate Limit Exceeded Randomize
Error: User Rate Limit Exceeded

Похожие вопросы