码迷,mamicode.com
首页 > 编程语言 > 详细

线程生产者与消费者

时间:2015-08-21 17:28:56      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:生产者与消费者

当货物2个的时候销售,还剩一个的时候生产

要点:在生产中等待销售,在销售中等待生产


生产者与消费者

public class A {

 int num;

 public int getNum() {

  return num;

 }

 //生产产品的方法;

 public synchronized void produce(){

  num++;

  System.out.println("生产了一个产品………………");

  this.notify();

 }

 //销售产品的方法:

 public synchronized void sale(){

  num--;

  System.out.println("销售了一个产品………………");

  this.notify();

 }

 //等待生产的方法;在生产中等待销售;

 public synchronized void waitforproduce() throws InterruptedException{

  while(num<=1){

   this.wait();

  }

 }

 //等待销售的方法;在销售中等待生产;

 public synchronized void waitforsale() throws InterruptedException{

  while(num>=2){

   this.wait();

  }

 }

 

}

 

package org.hyx;

 

public class Produce implements Runnable{

 A a;

 public Produce(A a){

  this.a=a;

 }

 @Override

 public void run() {

  while(true){

   try {

    a.waitforsale();

    System.out.println("正在生产品中………………");

    a.produce();

    System.out.println("当前还剩下产品数量为:"+a.getNum()+"个");

   } catch (InterruptedException e) {

    e.printStackTrace();

   }

  }

 }

}

 

package org.hyx;

 

public class Sale implements Runnable{

 A a;

 public Sale(A a){

  this.a=a;

 }

 @Override

 public void run() {

  while(true){

   try {

    Thread.sleep(100);

    a.waitforproduce();

    System.out.println("正在销售产品中………………");

    a.sale();

    System.out.println("当前剩下的数量为:"+a.getNum()+"个");

   } catch (InterruptedException e) {

    e.printStackTrace();

   }

  }

 }

}

 

package org.hyx;

 

public class Test {

 public static void main(String[] args) throws InterruptedException {

  A a=new A();

  Produce p=new Produce(a);

  Sale s=new Sale(a);

  Thread t=new Thread(p);

  Thread tt = new Thread(s);

  t.start();tt.start();

  Thread.sleep(2000);

  System.exit(0);

 }

}

 


本文出自 “爱吉” 博客,谢绝转载!

线程生产者与消费者

标签:生产者与消费者

原文地址:http://10079391.blog.51cto.com/10069391/1686779

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!