2

と の使用wait()に問題がありnotify()ます。一種のランデブーが必要です。

これは、小さなコードの一部です。

class A {
    private Rdv r;

    public A(Rdv r) {
        this.r = r;
    }

    public void someMethod() {
        synchronized(r) {
            r.wait();
        }

        // ***** some stuff never reached*****
    }
}

class Rdv { 
    private int added;
    private int limit;

    public Rdv(int limit) {
        this.added = 0;
        this.limit = limit;
    }

    public void add() {
        this.added++;

        if(this.added == this.limit) {
            synchronized(this) {
                this.notifyAll();
            }
        }
    }
}

class Main {
    public static void main(String[] args) {
        Rdv rdv = new Rdv(4);

        new Runnable() {
            public void run() {
                A a = new A(rdv);
                a.someMethod();
            }
        }.run();

        rdv.add();
        rdv.add();
        rdv.add();
        rdv.add();
    }
}

アイデアは、4 つのスレッドが「やあ、終わった」と言うまで待ってから、 の最後を実行することですsomeMethod()。しかしwait()、 にもかかわらず、 は永遠に続きますnotifyAll()

方法がわからない

4

4 に答える 4

6

wait() and notify() are not meant to be used directly but rather are primitives that better libraries use for low-level synchronization.

You should use a higher-level concurrency mechanism, such as CountDownLatch. You would want to use a CountDownLatch with a value of 4. Have each of the threads call the countDown() method of the latch, and the one you want to wait to call await().

private CountDownLatch rendezvousPoint = new CountDownLatch(4);

//wait for threads
rendezvousPoint.await();

//do stuff after rendezvous

//in the other 4 threads:
rendezvousPoint.countDown();
于 2012-01-20T17:11:09.357 に答える
3

ええと...あなたが実際にスレッドを開始していないことに気付いたのは私だけですか?

    new Runnable() {
        public void run() {
            A a = new A(rdv);
            a.someMethod();
        }
    }.run();

する必要があります

 Thread t = new Thread(
    new Runnable() {
        public void run() {
            A a = new A(rdv);
            a.someMethod();
        }
    });
 t.start();

4 つのスレッドを待機させたい場合は、これを 4 回実行する必要があります。

于 2012-01-20T17:18:24.510 に答える
2

自分をいじる代わりにwait()notify()CountDownLatch

于 2012-01-20T17:13:13.723 に答える
1

クラス A のすべてのインスタンスは、クラス Rdv の異なるインスタンスを持っているため、もちろん到達しません。

クラスAの静的変数としてRDVを使用する必要があります

于 2012-01-20T17:11:59.357 に答える