剑指offer-生产者消费者模型

模拟消费者和生产者的多线程生产。

1,Resource.java定义了一个数组,生产者向里面存入数据,消费者从里面取出数据。
2,Input.java ,生产者线程
3,Output.java, 消费者线程
//创建资源类 
Resource.java
package case98_ProducerConsumer;

//创建资源类
public class Resource {
	// 创建存数数组
	private int[] cell = new int[50];
	// inPos表示存入时的数组下标,outPos表示取出时数组下标
	private int inPos = 0, outPos = 0;
	// cell[]数组里面当前的有效数数量
	private int count = 0;

	// 存数
	public synchronized void put(int num) {
		try {
			while (count == cell.length)
				this.wait();
			cell[inPos] = num;
			System.out.println(">put< 线程正在执行,并且放入数据 cell[" + inPos + "]" + "=" + cell[inPos] + "......");
			inPos++;
			if (inPos == cell.length)
				inPos = 0;
			count++;
			this.notify();
		} catch (InterruptedException ie) {
			ie.printStackTrace();
		}
	}

	// 取数
	public synchronized int get() {
		int data = 0;
		try {
			while (count == 0)
				this.wait();
			data = cell[outPos];
			System.out.println(">get< 线程正在执行,并且取出数据 cell[" + outPos + "]" + "=" + cell[outPos]);
			outPos++;
			if (outPos == cell.length)
				outPos = 0;
			count--;
			this.notify();

		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return data;
	}

}


//创建存数线程,生产者
Input.java
package case98_ProducerConsumer;

//存数线程 ,生产者线程
public class Input implements Runnable {
	private Resource s;
	private int num = 0;

	// 构造函数
	public Input(Resource s) {
		this.s = s;
	}

	@Override
	public void run() {
		while (true) {
			s.put(num++);
			if (num > 191)
				num = 0;
		}
	}

}


//创建取数线程,消费者
Output.java
package case98_ProducerConsumer;

//取数线程, 消费者线程
public class Output implements Runnable {
	private Resource s;

	// 构造函数
	public Output(Resource s) {
		this.s = s;
	}

	@Override
	public void run() {
		while (true)
			s.get(); // 循环取出元素
	}

}


//创建主线程
ProducerConsumer.java
package case98_ProducerConsumer;

public class ProducerConsumer {

	public static void main(String[] args) {
		// 创建资源对象
		Resource s = new Resource();
		// 创建input对象
		Input in = new Input(s);
		// 创建output对象
		Output out = new Output(s);
		// 创建生产者线程
		new Thread(in).start();
		// 创建消费者线程
		new Thread(out).start();
	}

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值