我制作了一个程序并期待这样的输出:
A 1 A B 2 B C 3 C ...
电子 5 电子
这是我的代码,我认为我遇到了饥饿问题,请帮助我
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 通知前通知后
我想在这个程序进入饥饿之后