import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.applet.*; class Monitor { private int contents; private boolean available = false; // this is the condition variable. public synchronized int get() { if (available == false) { try { wait(); } catch (InterruptedException e) { } } available = false; notify(); return contents; } public synchronized void put(int value) { if (available == true) { try { wait(); } catch (InterruptedException e) { } } contents = value; available = true; notify(); } } class Producer extends Thread { private Monitor monitor; private int number; private Test5Frame test; public Producer(Monitor c, int number, Test5Frame tst) { monitor = c; this.number = number; test = tst; } public void run() { for (int i = 0; i < 10; i++) { monitor.put(i); test.text.append("Producer #" + this.number + " put: " + i+"\n"); } } } class Consumer extends Thread { private Monitor monitor; private int number; private Test5Frame test; public Consumer(Monitor c, int number, Test5Frame tst) { monitor = c; this.number = number; test = tst; } public void run() { int value = 0; for (int i = 0; i < 10; i++) { value = monitor.get(); test.text.append("Consumer #" + this.number + " got: " + value+"\n"); } } } class Test5Frame extends JFrame implements ActionListener { JTextArea text; JButton go; public Test5Frame () { setLayout(new BorderLayout()); add("Center", new JScrollPane(text = new JTextArea())); add("South",go = new JButton("Press Me")); go.addActionListener(this); text.setFont(new Font("TimesRoman", Font.PLAIN, 18)); } public void actionPerformed (ActionEvent evt) { text.setText(""); Monitor monitor = new Monitor(); Producer p1 = new Producer(monitor, 1, this); Consumer c1 = new Consumer(monitor, 1, this); p1.start(); c1.start(); } } public class Test5 extends Applet { public void init () { Test5Frame test = new Test5Frame(); test.setSize(350,700); test.setVisible(true); } }