Preview:
class Producer implements Runnable {
    Buffer buffer;

    Producer(Buffer buffer) {
        this.buffer = buffer;
        new Thread(this, "Producer").start();
    }

    public void run() {
        for (int i = 0; i < 5; i++) {
            buffer.put(i);
            System.out.println("Produced: " + i);
        }
    }
}

class Consumer implements Runnable {
    Buffer buffer;

    Consumer(Buffer buffer) {
        this.buffer = buffer;
        new Thread(this, "Consumer").start();
    }

    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Consumed: " + buffer.get());
        }
    }
}

public class SynchronizationExample {
    public static void main(String[] args) {
        Buffer buffer = new Buffer();
        new Producer(buffer);
        new Consumer(buffer);
    }
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter