博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
生产者消费者模式
阅读量:7296 次
发布时间:2019-06-30

本文共 1456 字,大约阅读时间需要 4 分钟。

package com.java.concurrent;/** * 生产者消费者模式 * @author fliay * */public class TestProductorAndConsumer {	public static void main(String[] args) {		Clerk c = new Clerk();		Productor pro = new Productor(c);		Consumer con = new Consumer(c);		new Thread(pro,"生产者A").start();		new Thread(con,"消费者B").start();		new Thread(pro,"生产者C").start();		new Thread(con,"消费者D").start();	}			}class  Clerk{	//初始化产品	private int product = 0;		//进货	public synchronized void get(){		if(product>=10){			System.out.println("产品已满!");			try {				this.wait();			} catch (InterruptedException e) {				// TODO Auto-generated catch block				e.printStackTrace();			}		}			this.notifyAll();			System.out.println(Thread.currentThread().getName()+":"+ ++product);					}		//卖货	public synchronized void sale(){		if(product<=0){			System.out.println("补货中!");			try {				this.wait();			} catch (InterruptedException e) {				// TODO Auto-generated catch block				e.printStackTrace();			}		}			this.notifyAll();			System.out.println(Thread.currentThread().getName()+":"+ --product);	}}class Productor implements Runnable{		private Clerk clerk;				public Productor(Clerk clerk) {		this.clerk = clerk;	}	public void run() {		for(int i=0;i<20;i++){			clerk.get();		}	}}class Consumer implements Runnable{		private Clerk clerk;				public Consumer(Clerk clerk) {		this.clerk = clerk;	}	public void run() {		for(int i=0;i<20;i++){			clerk.sale();		}	}}

  

转载于:https://www.cnblogs.com/fliay/p/7651095.html

你可能感兴趣的文章
2019.5.29 区块链论文翻译
查看>>
Centos6.6安装mysql记录
查看>>
OCP读书笔记(5) - 使用RMAN创建备份
查看>>
java的接口和抽象类区别
查看>>
能够提高PHP的性能的一些注意事项
查看>>
020-请你说一说app测试的工具
查看>>
软件测试2019:第五次作业—— 安全测试(含安全测试工具实验)
查看>>
SSM框架搭建总结(2)
查看>>
Python学习(19)正则表达式
查看>>
PHP中空字符串、0、null、empty和false之间的关系
查看>>
【深度学习篇】---CNN和RNN结合与对比,实例讲解
查看>>
201771010126 王燕《面向对象程序设计(Java)》第十二周学习总结
查看>>
XAML实例教程系列 - 资源(Resources)
查看>>
LWIP互联网资料汇总
查看>>
外贸术语
查看>>
网络传输流量控制策略小结
查看>>
上传大文件
查看>>
Mybatis面试集合(转)
查看>>
分布式系统的完整介绍(一)
查看>>
考点1
查看>>