Java 实现生产者和消费者

本文介绍了一个简单的生产者消费者模式实现,使用Java语言并通过线程间的等待和通知机制来协调生产和消费过程,确保资源的有效利用。

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

容器类:

package com.mjt.thread;

public class Collection {
	private String goods[] = new String[10];
	private int index = 0;
	public synchronized void put(String cargo) {
		if(index == 10) {
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		
		}
		goods[index] = cargo;
		index++;
		notify();
	}
	public synchronized String get() {
		if(index == 0) {
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		index --;
		String ret = goods[index];		
		notify();
		return ret;
	}
}
  生产者:

package com.mjt.thread;

public class Producer implements Runnable {
	int i = 1;
	private Collection collection;
	Producer(Collection collection) {
		this.collection = collection;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true) {
			collection.put("货物"+i);
			System.out.println("生产了"+"货物"+i);
			i++;
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}

消费者:

package com.mjt.thread;

public class Consumer implements Runnable {
	private Collection collection;
	Consumer(Collection collection) {
		this.collection = collection;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true) {			
			System.out.println("客户消费了"+collection.get());
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}

工厂类(生产车间)

package com.mjt.thread;

public class Factory {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Collection c = new Collection();
		new Thread(new Producer(c)).start();
		new Thread(new Consumer(c)).start();
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值