Skip to content

Instantly share code, notes, and snippets.

@hocyadav
Created December 27, 2023 09:50
Show Gist options
  • Save hocyadav/58586e209215cca3ce88c80d7c0d1dc8 to your computer and use it in GitHub Desktop.
Save hocyadav/58586e209215cca3ce88c80d7c0d1dc8 to your computer and use it in GitHub Desktop.
simple producer consumer pattern impl
import org.junit.jupiter.api.Test;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author Hariom Yadav
* @since 17-Nov-2023
*/
public class ProducerConsumerPatternTest {
@Test
public void foo() throws Exception{
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(5);
AtomicInteger atomic = new AtomicInteger(0);
Runnable producer = () -> {
while (true) {
try {
Thread.sleep(1000);
queue.put(atomic.incrementAndGet());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Producer = " + queue);
}
};
Runnable consumer = () -> {
while (true) {
try {
Thread.sleep(2000);
System.out.println("Consumer = " + queue.take());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
};
new Thread(producer).start();
new Thread(consumer).start();
// new Thread(consumer).start(); // ✅ we can create multiple producer and consumer and start all in parallel
Thread.sleep(444444);
}
}
@hocyadav
Copy link
Author

output

Producer = [1]
Consumer = 1
Producer = [2]
Producer = [2, 3]
Consumer = 2
Producer = [3, 4]
Producer = [3, 4, 5]
Consumer = 3
Producer = [4, 5, 6]
Producer = [4, 5, 6, 7]
Consumer = 4
Producer = [5, 6, 7, 8]
Producer = [5, 6, 7, 8, 9]
Consumer = 5
Producer = [6, 7, 8, 9, 10]
Consumer = 6
Producer = [7, 8, 9, 10, 11]
Consumer = 7
Producer = [8, 9, 10, 11, 12]
Consumer = 8
Producer = [9, 10, 11, 12, 13]
...
...

@hocyadav
Copy link
Author

hocyadav commented Dec 27, 2023

producer consumer pattern using own blocking queue : https://gist.github.com/hocyadav/5447026432d5ecfd6ce44ee1a2abcdd4

other thread que: simple approach to print even and odd number using 2 thread : https://gist.github.com/hocyadav/5ad0a32002dc52820c9a13e4301ae67a

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment