import java.util.Random; class Message { private String payload; private boolean empty = true; // syncronised read method used by consumer to read messages public synchronized String read() { while(empty) { } empty = true; return payload; } public synchronized void write(String payload) { while(!empty) { } this.payload = payload; empty = false; } } // Writer class or Producer class writes four messages class Writer implements Runnable { private Message message; public Writer(Message message) { this.message = message; } public void run() { String payload[] = { "Humpty Dumpty sat on a wall", "Humpty Dumpty had a great fall", "All the king's horses and all the king's men", "Couldn't put Humpty together again" }; // random class for random delay.. Random random = new Random(); for(int i=0; i< payload.length; i++) { message.write(payload[i]); // loop through all payloads try { Thread.sleep(random.nextInt(2000)); // upto two second sleep after writing a message } catch(InterruptedException e) { } } message.write("Finished"); } } // Reader class or producer class reads messages class Reader implements Runnable { private Message message; public Reader(Message message) { this.message = message; } public void run() { Random random = new Random(); for(String latestPayload = message.read(); !latestPayload.equals("Finished"); // wait for message to say "Finished" latestPayload = message.read()) { System.out.println(latestPayload); try { Thread.sleep(random.nextInt(2000)); } catch(InterruptedException e) { } } } } public class Main { public static void main(String[] args) { Message message = new Message(); (new Thread(new Writer(message))).start(); (new Thread(new Reader(message))).start(); } }