誰かがこのコードをコンパイルした後に、なぜ何かを待っているスレッドがあると思いますか? ID番号10,11,12のスレッドを1つずつ、50まで1つ増やしたい。 最終的には機能しますが、赤いボタン(終了)はまだ赤色です。つまり、まだプログラムが残っていますおそらく何かを待っています。指定されたスレッドでのJavaセマフォのインクリメント数
カウントが50の場合、リターンは動作し、メソッドから終了する必要があります。たぶんそれはありますが、十分ではありません。
public class App12 {
Semaphore sem1 = new Semaphore(1);
Semaphore sem2 = new Semaphore(0);
Semaphore sem3 = new Semaphore(0);
int count = 0;
public void inc() throws InterruptedException {
while (true) {
if (Thread.currentThread().getId() == 10) {
sem1.acquire();
if (count != 50) {
count++;
System.out.println("Thread" + Thread.currentThread().getId() + " has incremented " + count);
sem2.release();
} else
return;
}
if (Thread.currentThread().getId() == 11) {
sem2.acquire();
if (count != 50) {
count++;
System.out.println("Thread" + Thread.currentThread().getId() + " has incremented " + count);
sem3.release();
} else
return;
}
if (Thread.currentThread().getId() == 12) {
sem3.acquire();
if (count != 50) {
count++;
System.out.println("Thread" + Thread.currentThread().getId() + " has incremented " + count);
sem1.release();
} else
return;
}
}
}
public static void main(String[] args) {
App12 ap = new App12();
for (int i = 0; i < 3; i++) {
Thread th1 = new Thread(new Runnable() {
public void run() {
try {
ap.inc();
// dec3();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
th1.start();
}
}
}
コンストラクタに渡されるパラメータの使い方はわかりますか? –
ここでは、デフォルトのコンストラクタを使用しています。メソッドを静的に変更し、メソッドを呼び出すことができます。 – Victor
しかし、私はコンストラクタからここを通過するものはありません。 – Victor