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次 } } }
相关文章推荐
- jdk1.6.0_45的安装配置及环境变量的配置
- spring 注解 自动装配
- Java____Synchronized++之前线程进程学习链接
- spring与web整合(交鸡肋,因为有前台框架封装了servlet)
- Java环境变量配置
- java_笔记-9
- 学了近一个月的java web 感想
- Java 闭包机制
- spring复杂对象注入四种方式
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- Error: could not open 'C:/Program Files/Java/jre6/lib/i386/jvm.cfg' 的处理方法
- 用exe4j将java程序打包成exe格式
- SpringMVC文件的上传与下载
- SpringIOC_对象的多实例和单实例
- Java四种读取和创建XML文档的例子教程
- Java os.name
- jfinal spring 整合 集成 事物 spring-jfinal
- java中的垃圾收集算法
- jfinal集成spring cxf做webservice服务
- spring 注解事务配置