java实现生产者消费者算法

本文提供了一个使用Java实现的生产者消费者模式示例。通过synchronized关键字来控制线程同步,实现产品生产和消费的过程。生产者不断地创建产品并将其放入共享容器中,而消费者从该容器中取出并消费这些产品。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class testProducerConsumer {

	public static void main(String[] args) {
		ProductContainer pc = new ProductContainer();
		Producter producter = new Producter(pc);
		Consumer consumer = new Consumer(pc);
		new Thread(producter).start();
		new Thread(consumer).start();
	}

}

class Product {
	private int ID;

	Product(int ID) {
		this.ID = ID;
	}

	public String toString() {
		return "Product:" + ID;
	}
}

class ProductContainer {
	int index = 0;
	Product[] product = new Product[10];

	public synchronized void push(Product pro) {
		while (index == product.length) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notifyAll();
		product[index] = pro;
		index++;
	}

	public synchronized Product pop() {
		while(index == 0) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.notifyAll();
		index--;
		return product[index];
	}
}

class Producter implements Runnable {

	ProductContainer pc = null;

	Producter(ProductContainer pc) {
		this.pc = pc;
	}

	public void run() {
		for (int i = 0; i < 50; i++) {
			Product p = new Product(i);
			pc.push(p);
			System.out.println("生产了:" + p);
			try {
				Thread.sleep((int)(Math.random() * 1000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

class Consumer implements Runnable {
	ProductContainer pc = null;

	Consumer(ProductContainer pc) {
		this.pc = pc;
	}

	public void run() {
		for (int i = 0; i < 50; i++) {
			Product pro = pc.pop();
			System.out.println("消费了:" + pro);
			try {
				Thread.sleep((int)(Math.random() * 1000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值