Java生产者与消费者(上)



  本文来自刘兆贤_Java高级,Java底层探索,Android旅行-CSDN博客 ,引用必须注明出处!

         生产与消费者模式,是编程中最常用的模式之一,在多线程中应用比较明显。个人理解:在自助餐厅,厨师在不断做菜放桌子上,吃货不断从桌子上拿东西,这中间如果桌子上已经摆满那厨师要暂停工作 ,桌子上已没有食物则吃货要暂停拿东西吃。

先决条件,食材数量充足,桌子空间一定。 

本程序设计原则:由于synchronized加锁方法,使得内部的所有变量也被加锁;我们采取多线程操作,故中间要用sleep(为了把锁让给别人,比如A上厕所开启sleep模式,B就偷偷拿上锁溜进来,方便后再还锁给A,要保证B修改同一个资源的话,要在A sleep的时间内完成),以便其他线程可以使用(windows多线程亦采取同样设计原则),sleep很短的时间,故用户不会有停滞感。为结果清晰,producer和consumer共执行操作50次,则程序停止运行。

桌子:

count,即桌子空间一定,produce和consume均对count操作。当蛋糕数大于等于桌子数时,生产线程要等待;当蛋糕数少于或等于0时,消费线程要等待。notifyAll是唤醒所有线程,如果生产线程watit时,消费线程已经把cake吃光,则要唤醒生产线程,反之亦然,故用notifyAll,而notify仅唤醒当前线程,在这里是没有用的。

public class Table {

	private volatile int count;
	private int cake;
	private int stopCounts;

	public Table(int count) {
		// TODO Auto-generated constructor stub
		this.count = count;
	}

	public synchronized void produce(String threadName) throws InterruptedException {
		while (cake >= count) {
			System.out.println(threadName + " begin to wait !");
			wait();
			System.out.println(threadName + " stop waiting !");
		}
		System.out.println(threadName + " produce:" + ++cake);
		notifyAll();
		if (++stopCounts > 50) {
			System.out.println(threadName + " stop at last !");
			System.exit(0);
		}
	}

	public synchronized void consume(String threadName) throws InterruptedException {
		while (cake <= 0) {
			System.out.println(threadName + " begin to wait !");
			wait();
			System.out.println(threadName + " stop waiting !");

		}
		System.out.println(threadName + " consume:" + cake--);
		notifyAll();

		if (++stopCounts > 50) {
			System.out.println(threadName + " stop at last !");
			System.exit(0);
		}
	}
}

生产者:

生产蛋糕,一次停止1毫秒

public class Producer extends Thread {
	Table table;
	String threadName;

	public Producer(String string, Table table) {
		// TODO Auto-generated constructor stub
		this.table = table;
		this.threadName=string;
		this.setName(threadName);
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
		try {
			while (true) {
				table.produce(threadName);
				sleep(1);
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


消费者:

消费蛋糕,一次停止1毫秒

public class Consumer extends Thread {
	Table table;
	String threadName;

	public Consumer(String string, Table table) {
		// TODO Auto-generated constructor stub
		this.table = table;
		this.threadName=string;
		this.setName(threadName);
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
		try {
			while (true) {
				table.consume(threadName);
				sleep(1);
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


验证程序:

多线程

public class TestCP {
	public static void main(String[] args) {
		Table table = new Table(5);
		Thread p1 = new Producer("Produce1",table);
		Thread c1 = new Consumer("Consumer1",table);
		Thread p2 = new Producer("Produce2",table);
		Thread c2 = new Consumer("Consumer2",table);
		p1.start();
		c1.start();
		p2.start();
		c2.start();
	}
}

验证结果:

Produce1 produce:1            //Producer1先生产一只cake
Produce2 produce:2           //Producer2得到锁生产一只
Consumer1 consume:2          //Consumer1先消费一只
Consumer2 consume:1          //Consumer2得到锁也消费一只
Consumer1 begin to wait !    //Consumer1得到锁开始等待
Produce1 produce:1           //Producer1开始生产
Produce2 produce:2           // Producer2开始生产
Consumer2 consume:2          //Consumer2开始消费
Consumer1 stop waiting !     //当cake数大于0,Consumer1停止等待
Consumer1 consume:1          //Consumer1开始消费
Consumer1 begin to wait !    //当cake数等于0,Consumer1开始等待
Consumer1 consume:1          //Consumer1开始消费
Consumer1 begin to wait !    //当cake数等于0,Consumer1开始等待
Produce2 produce:1           //..............................  
Consumer1 stop waiting !  
Consumer1 consume:1  
Produce1 produce:1  
Consumer2 consume:1  
Consumer1 begin to wait !  
Consumer2 begin to wait !  
Produce1 produce:1  
Produce2 produce:2  
Consumer2 stop waiting !  
Consumer2 consume:2  
Consumer1 stop waiting !  
Consumer1 consume:1  
Consumer2 begin to wait !  
Consumer1 begin to wait !  
Produce1 produce:1  
Consumer1 stop waiting !  
Consumer1 consume:1  
Consumer2 stop waiting !  
Consumer2 begin to wait !  
Produce2 produce:1  
Consumer2 stop waiting !  
Consumer2 consume:1  
Consumer2 begin to wait !  
Produce1 produce:1  
Consumer1 consume:1  
Consumer2 stop waiting !  
Consumer2 begin to wait !  
Produce2 produce:1  
Consumer2 stop waiting !  
Consumer2 consume:1  
Produce1 produce:1  
Produce2 produce:2  
Consumer2 consume:2  
Consumer1 consume:1  
Consumer1 begin to wait !  
Consumer2 begin to wait !  
Produce1 produce:1  
Produce2 produce:2  
Consumer2 stop waiting !  
Consumer2 consume:2  
Consumer1 stop waiting !  
Consumer1 consume:1  
Consumer1 begin to wait !  
Produce2 produce:1  
Produce1 produce:2  
Consumer1 stop waiting !  
Consumer1 consume:2  
Consumer2 consume:1  
Consumer1 begin to wait !  
Produce1 produce:1  
Consumer2 consume:1  
Produce2 produce:1  
Consumer1 stop waiting !  
Consumer1 consume:1  
Consumer2 begin to wait !  
Consumer1 begin to wait !  
Produce1 produce:1  
Consumer1 stop waiting !  
Consumer1 consume:1  
Consumer2 stop waiting !  
Consumer2 begin to wait !  
Produce2 produce:1  
Consumer2 stop waiting !  
Consumer2 consume:1  
Consumer2 begin to wait !  
Produce2 produce:1  
Produce1 produce:2  
Consumer1 consume:2  
Consumer2 stop waiting !  
Consumer2 consume:1  
Consumer1 begin to wait !  
Produce2 produce:1  
Consumer1 stop waiting !  
Consumer1 consume:1  
Consumer2 begin to wait !  
Produce1 produce:1  
Produce1 stop at last !  

需要拓展知识的请关注: 

Java生产者与消费者(下)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
基于Java生产者消费者课程设计通常是关于多线程编程的实践项目。在该项目中,我们将设计一个生产者消费者的模型,模拟一个生产者生产商品,消费者消费商品的过程。 首先,我们需要创建一个商品类,该类包含商品的属性和方法,如商品的名称、价格、生产者消费者等。然后,创建一个生产者类和一个消费者类,分别用于表示生产者消费者的行为。 在生产者类中,我们使用Java的线程编程来实现生产者生产商品的过程。通过使用`wait()`和`notify()`方法,我们确保生产者只在商品缺乏的情况下进行生产。生产者线程在生产商品之前会检查商品队列是否已满,如果已满,则进入等待状态。当消费者消费商品后,生产者被唤醒,继续生产。每次生产一个商品,将其放入商品队列。 在消费者类中,我们使用Java的线程编程来实现消费者消费商品的过程。同样地,我们使用`wait()`和`notify()`方法来确保消费者只在商品充足的情况下进行消费。消费者线程在消费商品之前会检查商品队列是否为空,如果为空,则进入等待状态。当生产者生产商品后,消费者被唤醒,继续消费。每次消费一个商品,将其从商品队列中移除。 为了确保生产者消费者的同步操作,我们可以使用Java的`BlockingQueue`接口来实现商品队列。`BlockingQueue`是一个线程安全的队列,它提供了`put()`和`take()`方法来实现生产者消费者的阻塞操作。 此外,我们还可以对生产者消费者进行统计和监控,例如记录和显示每个生产者消费者的生产和消费过程,商品的生产和消费总量等信息。 通过这个基于Java生产者消费者课程设计,我们可以更好地理解和掌握多线程编程的概念和实践,以及如何有效地处理并发操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘兆贤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值