Created
January 19, 2016 09:58
-
-
Save RaffaeleSgarro/8f2434ac9e3ba130c480 to your computer and use it in GitHub Desktop.
Plain Java ProducerConsumer example
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
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