1

Java でマルチスレッドを学習するのに役立つ小さなプログラムを書いていますが、いくつかのシナリオを実装する方法に行き詰まっています。

このプログラムは、コーヒー ハウスもあるガソリン スタンドをシミュレートします。次のシナリオを作成できるようにしたい:

  • ガスポンプキューに人を追加します。
  • 同時に、喫茶店のレジ待ち行列に人を追加します。
  • ポンプ キュ​​ーの順番がレジの順番より前に到着した場合は、その人が何をするかを選択できるようにします (レジの順番にとどまってポンプ キュ​​ーを終了するか、その逆)。

これらの 2 つの状態の間をジャンプするにはどうすればよいですか?

これまでのところ、私はこれを持っています:

Person クラス

public class Person implements Runnable {

private GasPump pump;
private Cashier cashier;
...
public void pumpGas() throws InterruptedException {

    synchronized (this) {
        pump.addCarToQueue(this);
        wait();
    }

    synchronized (pump) {
        sleep((long) (Math.random() * 5000));
        pump.notify();
    }
}

public void buyCoffee() throws InterruptedException {

    synchronized (this) {
        cashier.addCustomerToQueue(this); // standing inline
        wait();
    }

    synchronized (cashier) {
        sleep((long) (Math.random() * 5000)); // paying at cashier
        cashier.notify();
    }
}
...
}

ガスポンプクラス

public class GasPump implements Runnable {

private Queue<Person> cars;
...
@Override
public void run() {
    while (gasStation.isOpen()) {
        if (!cars.isEmpty()) {
            Car firstCar = cars.poll();
            if (firstCar != null) {
                synchronized (firstCar) {
                    firstCar.notifyAll();
                }
            } else {
                // ?
            }

            synchronized (this) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
...
}

そしてキャッシャークラス

public class Cashier implements Runnable {

private Queue<Person> customers;
...
@Override
public void run() {
    while(coffeeHouse.isOpen()){
        if(!customers.isEmpty()){
            Car firstCustomer = customers.poll();
            if(firstCustomer != null){
                synchronized (firstCustomer) {
                    firstCustomer.notifyAll();
                }
            }

            synchronized (this) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
...
}
4

1 に答える 1