0

私はプログラムを作成し、次のような出力を期待しています:

A 1 a B 2 b C 3 c ...

E 5 e

これが私のコードです。飢餓の問題が発生していると思います。助けてください

class Product {
    static boolean flag1, flag2, flag3;

    synchronized void printLwrAlpha(char value) {
        // System.out.println(flag3+": inside lwr_alpha");
        if (!flag3)
            try {
                wait();
            } catch (Exception ex) {
                System.out.println(ex);
            }
        System.out.println(value);
        flag3 = false;
        flag1 = false;
        System.out.println("before notify");
        notify();
        System.out.println("after notify");
    }

    synchronized void printUprAlpha(char n) {
        // System.out.println(flag1+": inside upr_alpha");
        if (flag1)
            try {
                wait();
            } catch (Exception e) {
                System.out.println(e);
            }
        System.out.println(n);
        // System.out.println(num);
        flag1 = true;
        flag2 = true;
        notify();
    }

    synchronized void printNum(int num) {
        // System.out.println(flag2+": inside num");
        if (!flag2)
            try {
                wait();
            } catch (Exception e) {
                System.out.println(e);
            }
        // System.out.println(n);
        System.out.println(num);
        flag2 = false;
        flag3 = true;
        notify();
    }
}

class PrintNum implements Runnable {
    Product p;

    PrintNum(Product p) {
        this.p = p;
        new Thread(this, "Producer").start();
        try {
            Thread.sleep(1000);
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }

    public void run() {
        for (int i = 1; i <= 5; i++)
            p.printNum(i);
    }
}

class PrintLwrAlpha implements Runnable {
    Product p;
    static char ch = 'a';

    PrintLwrAlpha(Product p) {
        this.p = p;
        new Thread(this, "Producer").start();
        try {
            Thread.sleep(1000);
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }

    public void run() {
        for (int i = 1; i <= 5; i++) {
            char c = (char) (ch + (i - 1));
            p.printLwrAlpha(c);
        }
    }

}

class PrintUprAlpha implements Runnable {
    Product p;
    static char ch = 'A';

    PrintUprAlpha(Product p) {
        this.p = p;
        new Thread(this, "Producer").start();
        try {
            Thread.sleep(1000);

        } catch (Exception ex) {
            System.out.println(ex);
        }
    }

    public void run() {
        for (int i = 1; i <= 5; i++) {
            char c = (char) (ch + (i - 1));
            p.printUprAlpha(c);
        }
    }
}

public class MainClass1 {
    public static void main(String ar[]) {
        Product p = new Product();
        new PrintNum(p);
        new PrintUprAlpha(p);
        new PrintLwrAlpha(p);
    }

}

私はこの出力を得ています:

実行: A 1 B 2 C 3 D 4 E 5 a 通知前 通知後

このプログラムが飢餓に陥った後だと思います

4

2 に答える 2