Queue.java Source code

Java tutorial

Introduction

Here is the source code for Queue.java

Source

/*
 * Output:
 * 
 * Got: 0
 * Got: 0
 * Got: 0
 * ...
 */

class Queue {
    int n;

    synchronized int get() {
        System.out.println("Got: " + n);
        return n;
    }

    synchronized void put(int n) {
        this.n = n;
        System.out.println("Put: " + n);
    }
}

class Consumer implements Runnable {
    Queue q;

    Consumer(Queue q) {
        this.q = q;
        new Thread(this, "Consumer").start();
    }

    public void run() {
        while (true) {
            q.get();
        }
    }
}

public class MainClass {
    public static void main(String args[]) {
        Queue q = new Queue();
        new Consumer(q);
    }
}