Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Demonstration {
- public static void main(String args[]) throws Exception {
- test();
- }
- private synchronized static void safePrint(String message) {
- System.out.println(message);
- }
- private static void test() throws Exception {
- final BlockingQueue<Integer> queue = new BlockingQueue<Integer>(5);
- Thread t1 = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- for(int i = 0; i < 5; i++) {
- queue.enqueue(new Integer(i));
- safePrint("Enqueued: " + i);
- }
- } catch (InterruptedException ie) {
- }
- }
- }
- );
- Thread t2 = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- for(int i = 0; i < 3; i++) {
- safePrint("Dequeuedby T2: " + queue.deque());
- }
- } catch (InterruptedException ie) {
- }
- }
- }
- );
- Thread t3 = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- for(int i = 0; i < 2; i++) {
- safePrint("Dequeuedby T3: " + queue.deque());
- }
- } catch (InterruptedException ie) {
- }
- }
- }
- );
- t1.start();
- t2.start();
- t3.start();
- t1.join();
- t2.join();
- t3.join();
- }
- }
- // Blocking queue class
- class BlockingQueue<T> {
- private int currentSize = 0;
- private int head = 0, tail = 0;
- private int maxCapacity;
- T[] queue;
- Object lock = new Object();
- @SuppressWarnings("unchecked")
- public BlockingQueue(int maxCapacity) {
- this.maxCapacity = maxCapacity;
- this.queue = (T[]) new Object[maxCapacity];
- }
- public void enqueue(T value) throws InterruptedException {
- synchronized (lock) {
- while(currentSize == maxCapacity) {
- lock.wait();
- }
- if(tail == maxCapacity) {
- tail = 0;
- }
- queue[tail] = value;
- tail++;
- currentSize++;
- lock.notifyAll();
- }
- }
- public T deque() throws InterruptedException {
- T value = null;
- synchronized (lock) {
- while(currentSize == 0) {
- lock.wait();
- }
- if(head == maxCapacity) {
- head = 0;
- }
- value = queue[head];
- queue[head] = null;
- head++;
- currentSize--;
- lock.notifyAll();
- }
- return value;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement