私のインスタンスに、この結果を生成し、次の2つのクラスのコードを持っている:のJavaスレッドの同期問題
Wainting for calculation to complete...
Calculator thread says HELLO!
T1 says that total is 10
Wainting for calculation to complete...
Wainting for calculation to complete...
今のスレッドが待っているが、誰もがそれらを通知するつもりはありません。 "Calculator thread"が起動する前に、スレッドを強制的にT1からT3に強制的に実行させることはできますか?
public class Calculator implements Runnable{
private int total;
public int getTotal() {
return total;
}
@Override
public void run() {
synchronized (this) {
for (int i = 0; i < 5; i++) {
total += i;
}
System.out.println(Thread.currentThread().getName() + " says HELLO!");
notifyAll();
}
}
}
import static java.lang.System.out;
public class Reader implements Runnable{
private Calculator c;
public Reader(Calculator calc) {
c = calc;
}
public Calculator getCalculator() {
return c;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
Reader read = new Reader(calc);
Thread thread1 = new Thread(read);
Thread thread2 = new Thread(read);
Thread thread3 = new Thread(read);
thread1.setName("T1");
thread2.setName("T2");
thread3.setName("T3");
thread1.start();
thread2.start();
thread3.start();
Thread calcThread = new Thread(read.getCalculator());
calcThread.setName("Calculator thread");
calcThread.start();
}
}
@Override
public void run() {
synchronized (c) {
try {
out.println("Wainting for calculation to complete...");
c.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
out.println(Thread.currentThread().getName() + " says that " + "total is " + c.getTotal());
}
}
}
thread3.start()の後にThread.sleep()を追加できますが、これは適切な解決策ではないと考えています。 – nyxz
wait/notifyを使用するのではなく、java.util.concurrentのデバッグされたユーティリティを使用して、アプリケーションを完全に再設計してください。あなたの本当のアプリケーションが何であるかははっきりしていないので、あなたが使っているべきことを本当に教えてくれません。 – toto2
@toto:wait/notifyを使うべきではありません。それらはシンプルで魅力的なプリミティブです。 java.util.concurrentクラスは、同じクラスのラッパーです。私は読み書きロック、障壁、ラッチなどのより高いレベルの構造がこれらのクラスによって提供されることに同意します。しかし、単純なハンマーで十分である場合はアンビルを使用するべきではありません。 –