我目前停留在一個點功課,並想知道是否有人能幫助 -的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()方法中 –