/* * Mailbox.java * * 1.0 * * 000908 * * Leif Lindbäck. * */ public class Mailbox { private int mail; private boolean full = false; /** * Sends the mail. */ public synchronized void setMail(int m) { while (full) try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } mail = m; full = true; notifyAll(); } /** * Returns the mail. */ public synchronized int getMail() { while (!full) try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } full = false; notifyAll(); return mail; } /** * Tests the mailbox. */ public static void main( String[] args ) { Mailbox mb = new Mailbox(); new Thread( new Producer( mb ) ).start(); new Thread( new Consumer( mb ) ).start(); } } /** * A thread that puts mail in the mailbox. */ class Producer implements Runnable { private Mailbox mb; /** * Constructs a Runnable that puts mail in the specified mailbox. */ public Producer( Mailbox mb ) { this.mb = mb; } /** * Prints messages and puts them in the mailbox. */ public void run() { int mailNo = 0; for (;;) { System.out.println( "<<>>>>taking mail no " + mb.getMail() ); } } }