You make sure that only the consumer is waiting, so that notify will only notify the consumer.
By the way, why do you want the producer to wait?
Add a lock to the queue, and then create two Conditions, one is full, which handles the situation when the queue is full; the other is empty, which handles the situation when the queue is empty.
The operation process is as follows:
Producer:
1. Obtain lock
2. Check whether the queue is full. If it is full, wait for the full condition until awakened by the consumer
3. Add elements to the queue
4. notify empty condition, wake up a consumer
5. Release the lock
Consumer:
1. Obtain lock
2. Check whether the queue is empty. If it is empty, wait for the empty condition until awakened by the producer
3. Remove an element from the queue
4. notify full condition, wake up a producer
5. Release the lock.
Keep in mind that Condition is not a lock, and there is no "locking" of Condition.
The thread awakened by notify is random, so there is usually no way to specify who is awakened.
Based on my level of knowledge, I think there are two ways to do it:
1. Set the priority of the consumer thread and use notifyAll to increase the probability of the consumer thread obtaining resources;
2. It is to ensure that after the producer finishes executing, only the consumer is waiting;
You make sure that only the consumer is waiting, so that notify will only notify the consumer.
By the way, why do you want the producer to wait?
Add a lock to the queue, and then create two Conditions, one is full, which handles the situation when the queue is full; the other is empty, which handles the situation when the queue is empty.
The operation process is as follows:
Producer:
1. Obtain lock
2. Check whether the queue is full. If it is full, wait for the full condition until awakened by the consumer
3. Add elements to the queue
4. notify empty condition, wake up a consumer
5. Release the lock
Consumer:
1. Obtain lock
2. Check whether the queue is empty. If it is empty, wait for the empty condition until awakened by the producer
3. Remove an element from the queue
4. notify full condition, wake up a producer
5. Release the lock.
Keep in mind that Condition is not a lock, and there is no "locking" of Condition.
The thread awakened by notify is random, so there is usually no way to specify who is awakened.
Based on my level of knowledge, I think there are two ways to do it:
1. Set the priority of the consumer thread and use notifyAll to increase the probability of the consumer thread obtaining resources;
2. It is to ensure that after the producer finishes executing, only the consumer is waiting;
The thread cannot be specified, notify will wake up a thread waiting for the object.
The thread cannot be specified, notify will wake up a thread waiting for the object.