C, PHP, VB, .NET

Дневникът на Филип Петров


* Consumer-Producer – едностранна синхронизация с един консуматор и един производител

Публикувано на 28 ноември 2013 в раздел ПИК3 Java.

В този пример има споделен ресурс – чиния с храна. За нея няма ограничение какво количество храна ще поеме, затова producer (в случая Human) ще я пълни независимо дали е пълна или празна. Кучето, което яде от чинията, от своя страна ще гледа дали в купата има храна или не. Ако има храна, то ще я изяде. Ако няма, то ще изчака човека да го повика.

public class CP{
  static int dish = 0;
  static Dog sharo = new Dog();
  static Human ivan = new Human();
  public static void main(String[] args){
    sharo.start();
    ivan.start();
  }
}

class Dog extends Thread{
  int stomach;
  boolean feeded;
  public Dog(){
    this.stomach = 0;
    this.feeded = false;
  }
  public void run(){
    while(this.stomach <= 100){
      try{
        this.getFood();
      }
      catch(InterruptedException e){
        System.out.println("Dog will not feed full");
        break;
      }
    }
    System.out.println("Woof, woof!");
    this.feeded = true;
    CP.ivan.interrupt();
  }
  void getFood() throws InterruptedException{
    if(CP.dish ==0){
      synchronized(CP.ivan){
        System.out.println("Dog waiting for food");
        CP.ivan.wait();
      }
    }
    this.sleep((int)(Math.random()*500)); // Dog eats
    System.out.println("Dog eats "+CP.dish);
    this.stomach+=CP.dish;
    CP.dish = 0;
  }
}

class Human extends Thread{
  public void run(){
    do{
      try{
        this.cookFood();     
      }
      catch(InterruptedException e){
        System.out.println("Human stopped cooking");
        break;
      }
    }
    while(CP.sharo.feeded == false);
  }
  void cookFood() throws InterruptedException{
    this.sleep((int)(Math.random()*500)); // Human cooks
    CP.dish += 10;
    System.out.println("Human cooked 10");
    synchronized(this){
      this.notify();
    }
  }
}

 



Добави коментар

Адресът на електронната поща няма да се публикува


*