JAva生産者と消費者


package yzr.thread;

public class ProducerConsumer {

	public static void main(String[] args) {

		Contains c = new Contains();

		//          

		new Thread(new Producer(c)).start();

		new Thread(new Producer(c)).start();

		new Thread(new Producer(c)).start();

		new Thread(new Consumer(c)).start();

		new Thread(new Consumer(c)).start();

		new Thread(new Consumer(c)).start();

	}

}

class Producer implements Runnable {

	Contains c = null;

	public Producer(Contains c) {

		this.c = c;

	}

	@Override
	public void run() {

		for (int i = 0; i < 100; i++) {

			try {

				Thread.sleep(100);

			} catch (InterruptedException e) {

				e.printStackTrace();

			}

			c.push(" " + i + " ");

		}

	}

}

class Contains {

	int index = 0;

	int Max = 10;

	String[] s = new String[Max];

	public synchronized void push(String ss) {

		while (index == Max) {

			try {

				this.wait();

			} catch (InterruptedException e) {

				e.printStackTrace();

			}

		}

		this.notifyAll();

		s[index] = ss;

		System.out.println("   :" + s[index]);

		index++;

	}

	public synchronized void pop() {

		while (index == 0) {

			try {

				this.wait();

			} catch (InterruptedException e) {

				e.printStackTrace();

			}

		}

		this.notifyAll();

		index--;

		System.out.println("   :" + s[index]);

	}

}

class Consumer implements Runnable {

	Contains c = null;

	public Consumer(Contains c) {

		this.c = c;

	}

	@Override
	public void run() {

		for (int i = 0; i < 100; i++) {

			try {

				Thread.sleep(100);

			} catch (InterruptedException e) {

				e.printStackTrace();

			}

			c.pop();

		}

	}

}