Skip to content

Instantly share code, notes, and snippets.

@vigneshwaranr
Last active August 29, 2015 14:27
Show Gist options
  • Save vigneshwaranr/1a9656a4a8e08a2ba98a to your computer and use it in GitHub Desktop.
Save vigneshwaranr/1a9656a4a8e08a2ba98a to your computer and use it in GitHub Desktop.
Just my exercise to try out wait/notify in Java
import java.util.Random;
public class Main {
private static final MyBlockingQueue<Integer> queue = new MyBlockingQueue<>();
static class Producer extends Thread {
Producer(int i) {
super("Producer-" + i);
}
@Override
public void run() {
while (true) {
queue.put(new Random().nextInt(100));
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class Consumer extends Thread {
Consumer(int i) {
super("Consumer-" + i);
}
@Override
public void run() {
while (true) {
queue.take();
}
}
}
public static void main(String[] args) throws InterruptedException {
new Consumer(1).start();
new Consumer(2).start();
new Consumer(3).start();
new Producer(1).start();
new Producer(2).start();
new Producer(3).start();
//Thread.sleep(5 * 60 * 60 * 1000L);
}
}
import java.util.ArrayDeque;
import java.util.Queue;
/**
* Created by vigneshwaran on 22/08/15.
*/
public class MyBlockingQueue<E> {
private final Queue<E> queue = new ArrayDeque<>();
private final Object lock = new Object();
public E take() {
synchronized (lock) {
while (queue.isEmpty()) {
try {
System.out.println(Thread.currentThread().getName() + " waiting on take..");
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
E element = queue.poll();
System.out.println(Thread.currentThread().getName() + " woke up and returning.. " + element);
//lock.notify();
return element;
}
public void put(E element) {
System.out.println(Thread.currentThread().getName() + " adding element: " + element);
queue.offer(element);
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + " and notifying..");
lock.notify();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment