Skip to content

Instantly share code, notes, and snippets.

@codescv
Created February 15, 2014 10:45
Show Gist options
  • Save codescv/9017533 to your computer and use it in GitHub Desktop.
Save codescv/9017533 to your computer and use it in GitHub Desktop.
import java.util.LinkedList;
import java.lang.Thread;
class Test {
class BlockingQueue {
public BlockingQueue(int size) {
this.size = size;
}
public synchronized int get() {
try {
while (this.queue.size() == 0) {
wait();
}
} catch (Exception e) {}
if (this.queue.size() == this.size) {
notifyAll();
}
int result = this.queue.removeLast();
return result;
}
public synchronized void put(int val) {
try {
while (this.queue.size() == this.size) {
wait();
} } catch (Exception e) {}
if (this.queue.size() == 0) {
notifyAll();
}
this.queue.addFirst(val);
System.out.println("queue size: " + this.queue.size());
}
private LinkedList<Integer> queue = new LinkedList<Integer>();
private int size;
};
class Producer implements Runnable {
public Producer(BlockingQueue products) {
this.products = products;
}
public void run() {
int id = 0;
while (true) {
try {
Thread.sleep(1000);
} catch(Exception e) {}
System.out.println("produced product " + id);
products.put(id++);
}
}
private BlockingQueue products;
};
class Consumer implements Runnable {
public Consumer(BlockingQueue products) {
this.products = products;
}
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch(Exception e) {}
int p = products.get();
System.out.println("consumed product " + p);
}
}
private BlockingQueue products;
};
public void test() {
BlockingQueue q = new BlockingQueue(20);
Producer p = new Producer(q);
Consumer c = new Consumer(q);
new Thread(p).start();
new Thread(c).start();
}
public static void main(String[] args) {
Test t = new Test();
t.test();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment