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

本文共 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

你可能感兴趣的文章
面试题第二弹
查看>>
WPF MVVM 从Prism中学习设计模式之Event Aggregator 模式
查看>>
牛客暑假多校第六场 I Team Rocket
查看>>
年后跳槽如何准备?(转)
查看>>
Eclipse常用设置汇总
查看>>
python 字典dict类型合并(不能错过哦)
查看>>
程序练习1
查看>>
Eclipse换版本之后还用原先的Workplace,team只有Apply Patc指令了
查看>>
[MySQL]select和where子句优化
查看>>
html5 Web Workers
查看>>
八种排序整理(五)----简单选择排序
查看>>
<浮沉>读书笔记
查看>>
web-QQ(腾讯)-QZone-仿QQ投票和测试程序-数据库设计
查看>>
Cross-Origin Resource Sharing协议介绍
查看>>
IOS之应用程序设置
查看>>
关于__attribute__[转]
查看>>
Copy entire folder in Linux
查看>>
【OpenCV学习】图像亮度、对比度调节(伽马校正)
查看>>
shell 脚本编写注意事项
查看>>
html5离线应用application cache
查看>>