1

そのため、モニターを使用して Java で境界バッファーの問題を作成しましたが、プログラムの何が問題なのかわかりません。3 番目のループが終了する直前に、無限ループで実行し続けることがあります。ほとんどの場合、それは完全に実行されます。プログラムは単純で、1 つのプロデューサーと複数のコンシューマーについてです。助けていただければ幸いです。これは、コード全体を見つけることができる私の github へのリンクです。完全なコード

BoundedBuffer

public class BoundedBuffer {
    public BoundedBuffer ()
    {
        int numWorms = 10;
        int numBirds = 5;

        Dish dish = new Dish (numWorms);
        Parent parent = new Parent(dish);
        parent.start();
        Child child[] = new Child[numBirds];
        for (int i = 0; i < numBirds; i++)
        {
            child[i] = new Child (dish);
            child[i].start();
        }       
        for (int i = 0; i < numBirds; i++)
        {
            try {child[i].join();}
            catch (Exception ie) {System.out.println (ie.getMessage());}
        }

        System.out.println("bids done eating :D");
    }
}

public class Dish 
{
    int worms;
    int copy;
    public Dish (int worms)
    {
        this.worms = worms;
        copy = worms;
    }
    public synchronized void eat ()
    {
        if (worms <= 0)
        {

            waitForFull();
        }
        worms --;
        System.out.println("Bird " + Thread.currentThread().getName() + " has 
eaten."
                        + " The number of worms left is " + worms);

    }
    public synchronized void fill()
    {
        if (worms > 0)
        {
            waitForEmpty();
        }
        worms = copy;
        System.out.println ("Parent filled the dish");
        notifyAll();
    }
    public synchronized void waitForEmpty ()
    {
        while (worms > 0)
        {
            notifyAll();
            try {wait();}
            catch (Exception ie) {System.out.println (ie.getMessage());}
            }
}
    public synchronized void waitForFull ()
    {
        while (worms <= 0)
        {
            notifyAll();
            try {wait();}
            catch (Exception ie) {System.out.println (ie.getMessage());}
        }
    }
}
4

1 に答える 1