Created
December 27, 2023 09:50
-
-
Save hocyadav/58586e209215cca3ce88c80d7c0d1dc8 to your computer and use it in GitHub Desktop.
simple producer consumer pattern impl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
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
output