Frage

In exercise

Make a program where you have a fashion and a sewing machine, so the Operator enter data width and height, notify the sewing machine in order to perform their job.

The Operator receive data and process and notify machine. Machine receive data and finalizes the process.

However, when I run, the Maquina thread is not being notified and the machine and the Operator is in infinite loop receiving data.

public class Operator extends Thread {

    Scanner in = new Scanner(System.in);
    int altura, largura;
    public void run() {
        while(true) {
            synchronized (this) {
                System.out.print("Altura: ");
                altura = in.nextInt();
                System.out.print("Largura: ");
                largura = in.nextInt();
                notify();
            }
        }
    }

    public String getForma() {
        return "Forro de mesa : " + (altura * largura);
    }
}

public class Maquina extends Thread{

    private Operator c;

    public Maquina(Operator c) {
        this.c = c;
    }


    public void run() {
        while(true) {
            synchronized (c) {
                try {

                    System.out.println("Waiting shape...");
                    c.wait();

                    System.out.println("init drawn...");
                    Thread.currentThread().sleep(3000);

                    System.out.println("drawing...");
                    Thread.currentThread().sleep(3000);

                    System.out.println(c.getForma() + ", finalized");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
War es hilfreich?

Lösung

In running your code the problem seems to be that the "Waiting shape..." message is never reached. This surprises me but it seems like the while (true) { synchronized(c) is never letting the Maquina into the synchronized block.

Adding a small sleep at the front of the Operator.run() method fixes the problem. It gives time for the Maquina to get the lock and enter wait().

while (true) {
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return;
    }
    synchronized (this) {
        System.out.print("Altura: ");
        altura = in.nextInt();
        System.out.print("Largura: ");
        largura = in.nextInt();
        notify();
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top