I am trying to write produce and consumer that should print output in below order
consumer 1
produce 1
consumer 2
produce 2
But it's not giving outputs in order. To achieve order when using synchronized keyword, it's not printing even any output.
import java.util.concurrent.ArrayBlockingQueue;
import java.util.stream.IntStream;
public class ProducerAndCosumer {
ArrayBlockingQueue<Integer> blockingQueue ;
public ProducerAndCosumer(int capacity) {
this.blockingQueue = new ArrayBlockingQueue<Integer>(capacity);
}
public synchronized void consume(int data) {
System.out.println(" consumer " + data);
blockingQueue.offer(data);
}
public synchronized int produce() throws InterruptedException {
int data = blockingQueue.take();
System.out.println(" produce " + data);
return data;
}
public static void main(String[] args) throws InterruptedException {
ProducerAndCosumer pc = new ProducerAndCosumer(10);
Runnable run1 = new Runnable() {
@Override
public void run() {
System.out.println(" Entered consumer runner ");
IntStream.range(1, 20).forEach(pc::consume);
}
};
new Thread(run1).start();
Runnable run2 = new Runnable() {
@Override
public void run() {
System.out.println(" Entered producer runner ");
try {
for (int i = 0 ; i < 30 ; i++) {
pc.produce();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
new Thread(run2).start();
}
}
Please, suggest how can I resolve it. And one more question can we achieve it without wait and notify.