パターンごとにセマフォが必要です。最初のものは 1 に初期化する必要があり (そのスレッドを実行したいため)、他のすべては 0 に初期化する必要があります (最初にそれらのスレッドをブロックしたいため)。
すべてのスレッドは、セマフォの値を減らすことから始める必要があります (セマフォの値が 0 の場合、その呼び出しはブロックされます)。スレッド 1 の終了時に、2 番目のセマフォの値を増やす必要があります。スレッド 2 の最後で、3 番目のセマフォの値を増やす必要があります。最後のスレッドの最後で、最初のセマフォの値をもう一度増やして、最初からやり直す必要があります。
宿題をやりたくないので、2 つのスレッドのみの例を示します。
public static void main(String[] args) {
final Semaphore thread1Block = new Semaphore(1);
final Semaphore thread2Block = new Semaphore(0);
Thread thread1 = new Thread(new Runnable() {
public void run() {
while (true) {
// reduce the value of the first semaphore by one
// blocking if the value is 0
thread1Block.aquire();
System.out.print("11111111");
// increase the value of the second semaphore by one
thread2Block.release();
}
}
});
Thread thread2 = new Thread(new Runnable() {
public void run() {
while (true) {
// reduce the value of the second semaphore by one
// blocking if the value is 0
thread2Block.aquire();
System.out.print("2222");
// increase the value of the first semaphore by one
thread1Block.release();
}
}
});
// start the threads
thread1.start();
thread2.start();
}
編集
どうやら問題を誤解していたようです。注意が必要なのは、セマフォをカウンターとして使用することです。私は次のようにします (例として 2 つのスレッドのみ)。
public static void main(String[] args) {
final Semaphore s1 = new Semaphore(8);
final Semaphore s2 = new Semaphore(0);
Thread t1 = new Thread(new Runnable() {
public void run() {
while (true) {
s1.acquire();
System.out.print("1");
s2.release(4 * ((8 - s1.availablePermits()) / 8));
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
while (true) {
s2.acquire();
System.out.print("2");
s1.release(8 * ((4 - s2.availablePermits()) / 4));
}
}
});
t1.start();
t2.start();
}
秘訣は、各セマフォがカウンターとしても使用されることです。最初のセマフォの値が 0 の場合にのみ、2 番目のセマフォの値は 4 ずつ増加します。同様に、2 番目のセマフォの値が 0 の場合、最初のセマフォの値は 8 ずつ増加します。 .