您的位置:首页 > 编程语言 > Java开发

java多线程中,生产者消费者问题

2015-11-01 20:10 267 查看
java多线程中的经典案例,生产者与消费者问题
public class ProCusDemo {
/**
* @param args
*/
public static void main(String[] args) {
Company company = new Company();
//		Goods goods = new Goods();
new Thread(new ProThread(company), "生产者").start();
new Thread(new CusDemo(company), "消费者1").start();
new Thread(new CusDemo(company), "消费者2").start();
new Thread(new CusDemo(company), "消费者3").start();
}
}
package com.tlstudio.thread.homeword;
/**
* 实体类
*
* @author HDL
*
*/
public class Goods {
int id;// 商品编号
public Goods() {
}
public Goods(int id) {
super();
this.id = id;
}
@Override
public String toString() {
return "Goods [id=" + id + "]";
}
}
package com.tlstudio.thread.homeword;
/**
* 功能类
*
* @author HDL
*
*/
public class Company {
Goods[] goods = new Goods[10];
int count;
public synchronized void product(Goods good) {// 需要同步
while (count==goods.length ) {
System.out.println("仓库要满了,该卖了.......");
try {
wait();// 仓库满了等待消费
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
goods[count++] = good;
System.out.println(Thread.currentThread().getName()+"生产了" + good + ",现在共有" + count);
notify();// 通知开始消费了
}
public synchronized void custom() {// 需要同步
while (count ==0) {// 卖完了就等待
System.out.println("要卖完了,快点生产");
try {
wait();// 等待生产
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"卖出了" + goods[--count] + ",还有" + count + "个");
notify();// 通知开始生产了
}
}
package com.tlstudio.thread.homeword;
/**
* 线程类
*
* @author HDL
*
*/
public class ProThread implements Runnable {
Company company = new Company();
public ProThread(Company company) {
this.company = company;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
Goods goods = new Goods(i);
this.company.product(goods);// 生产20次
}
}
}
package com.tlstudio.thread.homeword;
/**
* 线程类
*
* @author HDL
*
*/
public class CusDemo implements Runnable {
Company company = new Company();
public CusDemo(Company company) {
this.company = company;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
this.company.custom();// 卖20次
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: