线程间通信之消费生产者模式二notify()
2014-08-26 18:16
183 查看
//生产消费者模式
public class ProcedureCustomerDemo
{
public static void main(String args[]){
Dug dug = new Dug();
Procedure procedure = new Procedure(dug);
Customer customer = new Customer(dug);
Thread t1 = new Thread(procedure);
Thread t2 = new Thread(customer);
t1.start();
t2.start();
}
}
class Dug
{
private int dugCount;
public synchronized void createDug(){
while(true){
if(dugCount>9){
//最多存放10只烤鸭
try{
System.out.println("烤鸭装盘已满,暂停制造");
this.wait();
}catch(Exception e){
}
}
System.out.println("生产第"+(++dugCount)+"只烤鸭");
try{
this.notify();
}catch(Exception e){
}
}
}
public synchronized void saleDug(){
while(true){
if(dugCount<1){
try{
System.out.println("烤鸭装盘已空,暂停卖出");
this.wait();
}catch(Exception e){
}
}
System.out.println("售出第"+(dugCount--)+"只烤鸭");
try{
this.notify();
}catch(Exception e){
}
}
}
}
class Procedure implements Runnable
{
private Dug dug;
public Procedure(Dug dug){
this.dug = dug;
}
public void run(){
dug.createDug();
}
}
class Customer implements Runnable
{
private Dug dug;
public Customer(Dug dug){
this.dug = dug;
}
public void run(){
dug.saleDug();
}
}
public class ProcedureCustomerDemo
{
public static void main(String args[]){
Dug dug = new Dug();
Procedure procedure = new Procedure(dug);
Customer customer = new Customer(dug);
Thread t1 = new Thread(procedure);
Thread t2 = new Thread(customer);
t1.start();
t2.start();
}
}
class Dug
{
private int dugCount;
public synchronized void createDug(){
while(true){
if(dugCount>9){
//最多存放10只烤鸭
try{
System.out.println("烤鸭装盘已满,暂停制造");
this.wait();
}catch(Exception e){
}
}
System.out.println("生产第"+(++dugCount)+"只烤鸭");
try{
this.notify();
}catch(Exception e){
}
}
}
public synchronized void saleDug(){
while(true){
if(dugCount<1){
try{
System.out.println("烤鸭装盘已空,暂停卖出");
this.wait();
}catch(Exception e){
}
}
System.out.println("售出第"+(dugCount--)+"只烤鸭");
try{
this.notify();
}catch(Exception e){
}
}
}
}
class Procedure implements Runnable
{
private Dug dug;
public Procedure(Dug dug){
this.dug = dug;
}
public void run(){
dug.createDug();
}
}
class Customer implements Runnable
{
private Dug dug;
public Customer(Dug dug){
this.dug = dug;
}
public void run(){
dug.saleDug();
}
}
相关文章推荐
- java线程通信 生产者与消费者模式
- 在并发编程中使用生产者和消费者模式能够解决绝大多数并发问题。该模式通过平衡生产线程和消费线程的工作能力来提高程序的整体处理数据的速度。
- 【Java】线程wait() notify()通信 实现生产者 消费者问题
- java多线程同步以及线程间通信详解&消费者生产者模式&死锁&Thread.join()(多线程编程之二)
- java多线程同步以及线程间通信详解&消费者生产者模式&死锁&Thread.join()(多线程编程之二)
- java多线程同步以及线程间通信详解&消费者生产者模式&死锁&Thread.join()(多线程编程之二)
- Java多线程之线程间通信--生产者/消费者模式
- [知了堂学习笔记]_线程通信(生产者和消费者模式)
- 线程通信之生产者消费者间wait()、notify实现
- python生产者与消费者模式:队列实现线程通信、ThreadLocal、GIL
- java wait/notify 生产者消费模式
- 多线程五,线程间通信3,wait、notify,notifyAll方法,生产者和消费者问题(14,毕向东老师)
- 多线程基础3-死锁、线程通信、生产者消费者模式
- 线程通信,wait()与notify()的运用
- 35.黑马程序员-线程间通信(生产者消费者)
- Java线程(三):线程协作-生产者/消费者模式
- 线程通信,生产者消费者问题(Java)
- wait()与notify()实现线程间的通信
- 线程间通信-生产者消费者
- 生产者-消费者模式 系列 之一 Sychronized,Notify,Wait 篇