多线程:生产者消费者实例

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生产者消费者实例
 */
public class ProducerAndConsumer {

	public static void main(String[] args) {
		Bakery bakery = new Bakery();
		Producer producer = new Producer(bakery);
		Consumer consumer = new Consumer(bakery);
		Thread t1 = new Thread(producer);
		Thread t2 = new Thread(producer);
		Thread t3 = new Thread(consumer);
		Thread t4 = new Thread(consumer);
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}

}

/**
 * 定义面包房
 */
class Bakery {
	private int count = 1;
	private String name;
	// 定义是否有面包
	private boolean flag;

	// 定义生产者和消费者线程锁
	Lock lock = new ReentrantLock();
	// 定义生产者和消费者的监视器
	private Condition pro_con = lock.newCondition();
	private Condition con_con = lock.newCondition();

	/**
	 * 生产面包方法
	 */
	public void produceBread(String name) {
		lock.lock();
		try {
			while (flag)
				try {
					pro_con.await();
				} catch (InterruptedException e) {
				}
			this.name = count + "个" + name;
			count++;
			System.out.println(Thread.currentThread().getName() + "面包房生产了第"
					+ this.name);
			this.flag = true;
			con_con.signal();
		} finally {
			// 必须进行锁的释放,否者可能代码中可能出现的异常,导致造成死锁等线程安全问题
			lock.unlock();
		}
	}

	/**
	 * 售卖面包方法
	 */
	public void consumeBread() {
		lock.lock();
		try {
			while (!flag)
				try {
					con_con.await();
				} catch (InterruptedException e) {
				}
			System.out.println(Thread.currentThread().getName() + "消费者买了第"
					+ this.name);
			this.flag = false;
			pro_con.signal();
		} finally {
			// 必须进行锁的释放,否者可能代码中可能出现的异常,导致造成死锁等线程安全问题
			lock.unlock();
		}
	}
}

class Producer implements Runnable {
	private Bakery bakery;

	Producer(Bakery bakery) {
		this.bakery = bakery;
	}

	@Override
	public void run() {
		while (true)
			bakery.produceBread("面包");
	}

}

class Consumer implements Runnable {
	private Bakery bakery;

	Consumer(Bakery bakery) {
		this.bakery = bakery;
	}

	@Override
	public void run() {
		while (true)
			bakery.consumeBread();
	}

}

发布了73 篇原创文章 · 获赞 3 · 访问量 4万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览