Skip to content

Instantly share code, notes, and snippets.

@RaffaeleSgarro
Created January 19, 2016 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RaffaeleSgarro/8f2434ac9e3ba130c480 to your computer and use it in GitHub Desktop.
Save RaffaeleSgarro/8f2434ac9e3ba130c480 to your computer and use it in GitHub Desktop.
Plain Java ProducerConsumer example
package stackoverflow;
import java.util.LinkedList;
import java.util.Queue;
public class ProducerConsumer {
public static void main(String... args) throws Exception {
final Object lock = new Object();
final Queue<Long> data = new LinkedList<>();
Thread producer = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(500);
synchronized (lock) {
long val = System.currentTimeMillis();
data.add(val);
System.out.println("Produced: " + val);
lock.notifyAll();
}
} catch (InterruptedException e) {
System.out.println("Terminating producer");
Thread.currentThread().interrupt();
}
}
});
Thread consumer = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
synchronized (lock) {
while (data.peek() == null) {
try {
lock.wait();
} catch (InterruptedException e) {
System.out.println("Terminating consumer");
Thread.currentThread().interrupt();
break;
}
}
if (!Thread.currentThread().isInterrupted()) {
long val = data.poll();
System.out.println("Consumed: " + val);
}
}
}
});
producer.setName("producer");
producer.setDaemon(true);
producer.start();
consumer.setName("consumer");
consumer.setDaemon(true);
consumer.start();
int runtimeSeconds = 3;
System.out.println("Running producer and consumer for " + runtimeSeconds + " seconds");
Thread.sleep(runtimeSeconds * 1000);
producer.interrupt();
consumer.interrupt();
producer.join();
consumer.join();
System.out.println("Program ended");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment