java 生产者消费者

ProduceCusomer.java

package com.juc.lock;

import java.util.Vector;

/**
 * 
 * @author mayanli
 *
 */
public class ProduceCusomer {

	public static void main(String[] args) {
		Vector<String> apples = new Vector<String>();
		new Thread(new Producer(apples)).start();
		new Thread(new Customer(apples)).start();
	}

}

/**
 * producer
 * 
 * @author mayanli
 *
 */
class Producer implements Runnable {
	private Vector<String> apples;

	public Producer(Vector<String> apples) {
		this.apples = apples;
	}

	@Override
	public void run() {

		while (true) {

			synchronized (apples) {
				if (apples.size() >= 11300) {
					try {
						apples.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				} else {
					System.err.println("add one" + apples.size());
					apples.add("apple");
					try {
						Thread.sleep(100);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.err.println("释放锁P");
					apples.notify();
				}
			}
		}

	}
}

/**
 * customer
 * 
 * @author mayanli
 *
 */
class Customer implements Runnable {
	private Vector<String> apples;

	public Customer(Vector<String> apples) {
		this.apples = apples;
	}

	@Override
	public void run() {
		while (true) {
			synchronized (apples) {
				if (apples.size() <= 0) {
					try {
						apples.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				} else {
					System.err.println("remove one" + apples.size());
					apples.remove(0);
					try {
						Thread.sleep(100);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.err.println("释放锁C");
					apples.notify();
				}
			}
		}
	}
}


你可能感兴趣的:(java 生产者消费者)