我目前停留在一个点功课,并想知道是否有人能帮助 -的Java信号量syncronize印刷筛选
我必须使用信号量在Java中印字母从2个线程同步 - 一个打印“ A“和一个打印”B“。我不能打印出超过2连续相同的字符,所以输出应该看起来像
AABABABABABBABABABABAABBAABBABABA
目前,我有3个信号灯,二进制互斥设置为1,和信号计数,和我的线程类是这个样子 -
public void run() {
while (true) {
Time.delay(RandomGenerator.integer(0,20));
Semaphores.mutex.down();
System.out.println (produce());
if (printCount > 1)
{ printCount = 0;
Semaphores.mutex.up();
Semaphores.printB.up();
}
}
}
public String produce() {
printCount++;
return "A";
}
public void run() {
while (true) {
Time.delay(RandomGenerator.integer(0,20));
Semaphores.mutex.down();
System.out.println (produce());
if (printCount > 1)
{ printCount = 0;
Semaphores.mutex.up();
Semaphores.printA.up();
}
}
}
public String produce() {
printCount++;
return "B";
}
但无论我尝试,要么死锁,或它似乎是唯一的工作最多打印2连胜,但似乎总是在打印3每隔一排又一排!
任何帮助非常感谢,不看代码或任何东西只是几个指针如果可能的话:)
虽然这不符合要求,但您可以使用Peterson算法实现此目的。 – nhahtdh
将不会如果条件总是正确的? – twodayslate
一旦printCount大于1,我将它重置为0,以便它可以重新开始,在produce()方法中 –