生产者与消费者

package com.ccl.thread;

public class ProducerCustomer {

	/**
	 * @author changlun.cheng
	 * @param args
	 * @see Product/Producer/Customer/Store 生产者与消费者
	 */
	public static void main(String[] args) {

		Store s = new Store();

		for (int i = 0; i < 4; i++) {

			Producer pi = new Producer(s, i);
			Thread tp = new Thread(pi);
			tp.start();

			Customer c = new Customer(s);
			Thread tc = new Thread(c);
			tc.start();
		}

	}

}

生产者类:

package com.ccl.thread;

public class Producer implements Runnable {

	public Store s;

	public int rank;

	public Producer(Store s, int rank) {
		this.rank = rank;
		this.s = s;
		System.out.println("new a producer.");
	}

	@Override
	public void run() {

		for (int i = 1; i < 41; i++) {

			make(i + rank * 40);

		}

	}

	private void make(int id) {

		Product p = new Product(id);
		s.push(p);

		try {

			Double d = Math.random() * 500;
			Thread.sleep(d.longValue());
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}


产品类:


package com.ccl.thread;

public class Product {

	public int Id;

	public Product(int id) {

		Id = id;
		System.out.println("new a product . this is id: " + Id);

	}

}


消费者类:

package com.ccl.thread;

public class Customer implements Runnable {

	public Store s;

	public Customer(Store s) {

		this.s = s;
		System.out.println("come on a customer.");
	}

	@Override
	public void run() {

		for (int i = 0; i < 40; i++) {

			eat();

		}
	}

	private void eat() {

		Product p = s.pop();
		System.out.println("customer eat " + p.Id);

		try {
			Double d = Math.random() * 1000;
			Thread.sleep(d.longValue());
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}


仓库类:

package com.ccl.thread;

public class Store {

	private int index = 0;

	public Store() {
	}

	private Product[] array = new Product[10];

	public synchronized void push(Product p) {

		while (index == array.length) {

			try {
				this.wait();
				System.out.println("a producer wait.");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}

		this.notifyAll();
		array[index] = p;
		index++;

	}

	public synchronized Product pop() {

		while (index == 0) {

			try {
				this.wait();
				System.out.println("a customer wait.");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}

		this.notifyAll();
		index--;
		return array[index];
	}

}




  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值