Posiadam klasę, której zadaniem jest wyświetlanie sekwencji liter "ABC" o długości zadeklarowanej w programie. Program prezentuje się następująco:
import java.util.concurrent.Semaphore;
public class SemaphoresABC {
private static final int COUNT = 10;
private static final int DELAY = 5;
private static final Semaphore a = new Semaphore(1, true);
private static final Semaphore b = new Semaphore(0,true);
private static final Semaphore c = new Semaphore(0, true);
public static void main(String[] args) {
new A().start();
new B().start();
new C().start();
}
private static final class A extends Thread {
@Override
@SuppressWarnings("SleepWhileInLoop")
public void run() {
try {
for (int i = 0; i < COUNT; i++) {
a.acquire();
System.out.print("A ");
b.release();
Thread.sleep(DELAY);
}
} catch (InterruptedException ex) {
System.out.println("Ooops...");
Thread.currentThread().interrupt();
throw new RuntimeException(ex);
}
System.out.println("\nThread A: I'm done...");
}
}
private static final class B extends Thread {
@Override
@SuppressWarnings("SleepWhileInLoop")
public void run() {
try {
for (int i = 0; i < COUNT; i++) {
b.acquire();
System.out.print("B ");
c.release();
Thread.sleep(DELAY);
}
} catch (InterruptedException ex) {
System.out.println("Ooops...");
Thread.currentThread().interrupt();
throw new RuntimeException(ex);
}
System.out.println("\nThread B: I'm done...");
}
}
private static final class C extends Thread {
@Override
@SuppressWarnings("SleepWhileInLoop")
public void run() {
try {
for (int i = 0; i < COUNT; i++) {
c.acquire();
System.out.print("C ");
a.release();
Thread.sleep(DELAY);
}
} catch (InterruptedException ex) {
System.out.println("Ooops...");
Thread.currentThread().interrupt();
throw new RuntimeException(ex);
}
System.out.println("\nThread C: I'm done...");
}
}
}
Chciałbym jednak go zmodyfikować, aby dana litera się powtarzała, przykładowo aby stworzyć sekwencję "ABCA", czy "BCAAB". Jak mogę to osiągnąć?